Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting python datetime to timestamp and back in UTC still uses local timezone

To get a naive datetime object that represents time in UTC from "seconds since the epoch" timestamp:

from datetime import datetime

utc_dt = datetime.utcfromtimestamp(ts)

If you want to get an aware datetime object for UTC timezone:

import pytz

aware_utc_dt = utc_dt.replace(tzinfo=pytz.utc)

To convert it to some other timezone:

tz = pytz.timezone('America/Montreal')
dt = aware_utc_dt.astimezone(tz)

To convert the timestamp to an aware datetime object in the given timezone directly:

dt = datetime.fromtimestamp(ts, tz)

Hmm I found the answer here: How to specify time zone (UTC) when converting to Unix time? (Python)

In [101]: ts = calendar.timegm(datetime(2010, 7, 1, tzinfo=pytz.utc).timetuple())

In [102]: datetime.fromtimestamp(ts, tz=pytz.utc)
Out[102]: datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>)