Skip to content

Instantly share code, notes, and snippets.

@mattharley
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattharley/8b49c505db26700762ae to your computer and use it in GitHub Desktop.
Save mattharley/8b49c505db26700762ae to your computer and use it in GitHub Desktop.
Django and Timezones Quick Reference Guide

Django Timezone Quick Reference

Timezones hurtz my brains

import datetime
import pytz

from django.utils import timezone

# Let's be in Perth time
perth = pytz.timezone('Australia/Perth')

# Change from a naive timezone to timezone-aware

utcnaive = datetime.datetime.utcnow()
# datetime.datetime(2014, 7, 24, 7, 13, 15, 754516)
utcaware = utcnaive.replace(tzinfo=pytz.utc)
# datetime.datetime(2014, 7, 24, 7, 13, 15, 754516, tzinfo=<UTC>)
# OR
utcaware = pytz.utc.localize(utcnaive)
# datetime.datetime(2014, 7, 24, 7, 13, 15, 754516, tzinfo=<UTC>)

# Change UTC <----> Local
perthaware = timezone.localtime(utcaware, perth)
# datetime.datetime(2014, 7, 24, 15, 13, 15, 754516, tzinfo=<DstTzInfo 'Australia/Perth' WST+8:00:00 STD>)

# Change Local <----> UTC
utcaware = timezone.localtime(perthaware, pytz.utc)
# datetime.datetime(2014, 7, 24, 7, 13, 15, 754516, tzinfo=<UTC>)

## Change to naive (non timezone-aware)
perthnaive = timezone.make_naive(perthaware, perth)
# datetime.datetime(2014, 7, 24, 15, 13, 15, 754516)

perthnaive = timezone.make_naive(utcaware, perth)
# datetime.datetime(2014, 7, 24, 15, 13, 15, 754516)

perthnaive = perthaware.replace(tzinfo=None)
# datetime.datetime(2014, 7, 24, 15, 13, 15, 754516)

utcnaive = timezone.make_naive(perthaware, pytz.utc)
# datetime.datetime(2014, 7, 24, 7, 13, 15, 754516)

References

Django 1.7 docs for timezone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment