Converting python datetime to timestamp and back in UTC still uses local timezone -
i'm working code gives me utc timestamps , want convert them appropriate datetimes. unfortunately when test simple cases pytz datetime has added 6 hours (the cst offset utc). need keep timezone data correct because calculating difference between other timezones well. ideas why , how convert utc timestamp utc datetime?
in [1]: import pytz in [2]: datetime import datetime in [3]: import time in [4]: datetime.fromtimestamp(time.mktime(datetime(7,1,1, tzinfo=pytz.utc).timetuple()), tz=pytz.utc) out[4]: datetime.datetime(2007, 1, 1, 6, 0, tzinfo=<utc>) in [5]: datetime.fromtimestamp(time.mktime(datetime(7,1,1).utctimetuple()), tz=pytz.utc) out[5]: datetime.datetime(2007, 1, 1, 6, 0, tzinfo=<utc>) in [6]: datetime.fromtimestamp(time.mktime(datetime(7,1,1).utctimetuple())) out[6]: datetime.datetime(2007, 1, 1, 0, 0)
to naive datetime object represents time in utc "seconds since epoch" timestamp:
from datetime import datetime utc_dt = datetime.utcfromtimestamp(ts)
if want aware datetime object utc timezone:
import pytz aware_utc_dt = utc_dt.replace(tzinfo=pytz.utc)
to convert other timezone:
tz = pytz.timezone('america/montreal') dt = aware_utc_dt.astimezone(tz)
to convert timestamp aware datetime object in given timezone directly:
dt = datetime.fromtimestamp(ts, tz)
Comments
Post a Comment