Django Timezone Gotcha

Dealing with timezones is always a pain. I thought I solved that problem by using:

from django.utils import timezone

now =

This code gets the time in the timezone specified in your Django settings… or so I thought. When you render the time in a template, it works as expected.

But in your python code, a view for example, the time is in UTC. From the Django docs:

You should only use local time when you’re interacting with humans, and the template layer provides filters and tags to convert datetimes to the time zone of your choice.

I agree with that. However, I interact with humans in other layers besides the template layer. For example, I dynamically generate files and put a human readable timestamp in the file. Many of my users do everything in one timezone. They never think about other time zones or UTC. So writing the timestamp in UTC would just seem overly geeky and annoying to them.

Here is how to get the datetime in the local timezone:

import pytz
import datetime


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s