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
)?
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)
Here's is an actual code (built-in):
from datetime import datetime, timezone, timedelta
return datetime(yy, mm, dd, hh, min, ss, 0, timezone(timedelta(hours=5))) # +0500
# or
return datetime(yy, mm, dd, hh, min, ss, 0, timezone(timedelta(seconds=18000))) # +0500
I believe .astimezone() is what you want.
datetime.strptime("2013-03-21T14:19:42+0100", "%Y-%m-%dT%H:%M:%S%z").astimezone()
Should give you what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.