Wednesday, February 20, 2013

Python datetime timestamp conversion between timezones

Recently, I needed to deal with some datetime/timestamp conversion between timezones in Python.
from datetime import datetime, timedelta
from dateutil import tz

utc = tz.tzutc()
local = tz.tzlocal()

# http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python/8778548#8778548
def to_timestamp(dt_in_utc, epoch=datetime(1970, 1, 1, tzinfo=utc)):
    td = dt_in_utc - epoch
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 1e6

# datetime to utc, if the datetime has no tzinfo, treat it as local
def to_utc(dt):
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=local)
    return dt.astimezone(utc)
    
# utc timestamp to datetime
def to_datetime(timestamp, tz=local):
    return datetime.utcfromtimestamp(timestamp).replace(tzinfo=utc).astimezone(tz)