Last active
August 29, 2015 14:02
-
-
Save octaflop/3016d5eb65085339fc12 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# encoding: utf-8 | |
import pytz | |
import datetime | |
from django.utils import timezone | |
""" | |
campus is a django model | |
for these examples: | |
campus.tz = 'America/Denver' | |
naivetime = datetime.time(15, 00) | |
I am getting datetime.time(16, 00) which != datetime.time(15, 00) | |
when I run the following: | |
>>> naivetime = datetime.time(15, 00) | |
>>> utctime = campus_time_to_utc(campus, naivetime) | |
>>> campus_time = utc_time_to_campus(campus, utctime) | |
>>> naivetime == campus_time | |
→ returns False | |
""" | |
def campus_time_to_utc(campus, naivetime): | |
""" | |
based on a campus and a naive time, | |
convert the time to a naive utc for saving | |
""" | |
just_time = False | |
stdtime = timezone.datetime(2014, 01, 01, 00, 00) | |
utc = pytz.timezone('UTC') | |
tz = pytz.timezone(campus.tz) | |
# we can't associate time to tz without knowing the date | |
# this is due to dst | |
# we can assume that if this fx is being called, then | |
# the dst is based on a standard date and combine | |
if type(naivetime) == datetime.time: | |
naivetime = timezone.datetime.combine(stdtime, naivetime) | |
just_time = True | |
tztime = tz.localize(naivetime) | |
utctime = utc.normalize(tztime) | |
if just_time: | |
return utctime.replace(tzinfo=None).time() | |
return utctime.replace(tzinfo=None) | |
def utc_time_to_campus(campus, utctime): | |
""" | |
based on a campus and a stored naive utc time | |
return the local timezone-aware time | |
returns time if only receiving a datetime.time | |
""" | |
just_time = False | |
stdtime = timezone.datetime(2014, 01, 01, 00, 00) | |
utc = pytz.timezone('UTC') | |
tz = pytz.timezone(campus.tz) | |
if type(utctime) == datetime.time: | |
utctime = timezone.datetime.combine(stdtime, utctime) | |
just_time = True | |
utctime = utctime.replace(tzinfo=utc) | |
campus_time = tz.normalize(utctime) | |
if just_time: | |
return campus_time.time() | |
return campus_time | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment