Last active
December 10, 2015 08:40
-
-
Save boojums/c2e1ca09088c6ace46ea to your computer and use it in GitHub Desktop.
Quick demo of dealing with timestamps and timezones, which suck.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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