Skip to content

Instantly share code, notes, and snippets.

@boojums
Last active December 10, 2015 08:40
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 boojums/c2e1ca09088c6ace46ea to your computer and use it in GitHub Desktop.
Save boojums/c2e1ca09088c6ace46ea to your computer and use it in GitHub Desktop.
Quick demo of dealing with timestamps and timezones, which suck.
from calendar import timegm
import datetime
from django.utils.timezone import make_aware
import pytz
# Roundtrip a datetime to a timestamp (epoch, seconds) and back again
date = datetime.datetime(2015, 10, 25, 2)
timestamp = timegm(date.timetuple())
>>> 1445738400
# For a sanity check of epoch timestamps I used online converters like
# http://www.epochconverter.com/
# Use utcfromtimestamp rather than fromtimestamp
# This gives you a naive time but doesn't move it from UTC
datetime.datetime.utcfromtimestamp(timestamp)
>>> datetime.datetime(2015, 10, 25, 2, 0)
# If you use fromtimestamp you get a localized time instead
datetime.datetime.fromtimestamp(timestamp)
>>> datetime.datetime(2015, 10, 25, 3, 0)
# Additionally, if you call django's make_aware on a naive datetime at the DST
# transition, it will barf an AmbiguousTimeError (as it should)
make_aware(date)
>>> barf AmbiguousTimeError
# Solution is to set the timezone when you call make_aware
make_aware(date, timezone=pytz.UTC)
>>> datetime.datetime(2015, 10, 25, 2, 0, tzinfo=<UTC>)
# If a timestamp is received and assumed UTC and what we want is a timezone-aware
# datetime also in UTC, this works:
make_aware(dt.datetime.utcfromtimestamp(timestamp), timezone=pytz.UTC)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment