aPrOgRaMmEr aPrOgRaMmEr - 2 months ago 32
Python Question

Get UTC timestamp from time zone aware datetime object in Python

I have a datetime object that I created with

datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))
.
Please correct me if I'm wrong, but I believe that my datetime object is NOT naïve. How do I convert this datetime object to a UTC timestamp?

Answer

Use datetime.astimezone to get the same datetime in UTC (or any other timezone).

dt = datetime.datetime(year, month, day, hour, minute, tzinfo=pytz.timezone('US/Pacific'))
dt_utc = dt.astimezone(pytz.timezone('UTC'))
Comments