ILoveGit
ILoveGit

Reputation: 362

Get UTC timestamp from time zone aware datetime object in Python

I have a datetime object that I created withdatetime.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?

Upvotes: 4

Views: 2557

Answers (2)

ILoveGit
ILoveGit

Reputation: 362

non_naive_datetime_obj.astimezone(pytz.utc).timestamp()

Upvotes: 0

Tore Eschliman
Tore Eschliman

Reputation: 2507

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'))

Upvotes: 6

Related Questions