Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply timezone offset to datetime in Python

For a given date string such as 2009-01-01T12:00:00+0100 I want the UTC datetime object.

from datetime import datetime 
datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")

returns

datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))

I cannot believe there is no method in datetime or pandas for applying the timezone-related offset to the datetime and returning plain UTC datetime.

How can I apply the tzinfo offset/delta, so that the resulting timezone is plain UTC (tzinfo=None)?

like image 722
Michael Dorner Avatar asked Jan 01 '23 20:01

Michael Dorner


1 Answers

This feels a bit dirty but it does work

from datetime import datetime
orig_dt = datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z")  # datetime.datetime(2013, 3, 21, 14, 19, 42, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
utc_time_value = orig_dt - orig_dt.utcoffset()
utc_dt = utc_time_value.replace(tzinfo=None)  # datetime.datetime(2013, 3, 21, 13, 19, 42)
like image 128
Landar Avatar answered Jan 08 '23 05:01

Landar