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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With