Skip to content

Instantly share code, notes, and snippets.

@jholloway7
Created March 11, 2012 00:53
Show Gist options
  • Save jholloway7/2014290 to your computer and use it in GitHub Desktop.
Save jholloway7/2014290 to your computer and use it in GitHub Desktop.
Implementing a Python datetime localizer using python-dateutil
from dateutil import tz
def _convert_tz(val, from_tzinfo, to_tzinfo):
# Interpret the naive datetime as in the 'from' time zone
val = val.replace(tzinfo=from_tzinfo)
# Convert to specified time zone
val = val.astimezone(to_tzinfo)
# Make it a naive datetime again
val = val.replace(tzinfo=None)
return val
def convert_tz(val, from_zone, to_zone):
"""Converts a naive datetime object between two Olson time zones"""
return _convert_tz(val, tz.gettz(from_zone), tz.gettz(to_zone))
def localize(val, to_zone=None):
"""Localizes the specified datetime object from UTC to the given Olson time zone"""
to_tzinfo = tz.gettz(to_zone) if to_zone else tz.tzlocal()
return _convert_tz(val, tz.tzutc(), to_tzinfo)
def to_utc(val, from_zone=None):
"""Takes a naive datetime object presumed to be in the given Olson time zone and converts it to UTC."""
from_tzinfo = tz.gettz(from_zone) if from_zone else tz.tzlocal()
return _convert_tz(val, from_tzinfo, tz.tzutc())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment