I need to compare two date string and for that, I need to convert the date string to datetime object. An example of a date string is "2015-08-23T03:36:30-05:00". I am assuming "-05:00" is the timezone string. I could to convert the string to datetime using below approach:
import datetime
str = '2015-08-23T03:36:30-05:00'
datetime.datetime.strptime(str,"%Y-%m-%dT%H:%M:%S-%f:00")
I can see the value of microsecond
as 50000
which seems wrong to me as the -5:00 value is the timezone. What is the correct way to parse as I will be comparing two datetimes?
CodePudding user response:
You could use %z
to parse timezone info:
>>> from datetime import datetime, timezone
>>> datetime.strptime(str, "%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2015, 8, 23, 3, 36, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))
Then, if you want to convert this datetime to UTC (which I assume is your goal since you say you want to compare datetimes), you could use astimezone
method:
>>> datetime.strptime(str, "%Y-%m-%dT%H:%M:%S%z").astimezone(timezone.utc)
datetime.datetime(2015, 8, 23, 8, 36, 30, tzinfo=datetime.timezone.utc)
Back in string format:
>>> datetime.strptime(str, "%Y-%m-%dT%H:%M:%S%z").astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
'2015-08-23 08:36:30'