1

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

enter image description here

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?

1
  • %f is the parser directive for parsing the microseconds part of the timestamp. The UTC offset directive is %z, but it uses a format without colon. So, if you can adjust the source format, you can go with the standard directives. Otherwise, you might have to come up with a custom regular expression. Commented Apr 3, 2022 at 20:14

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

Comments

0

If your problem is that the initial time is in the wrong time zone, you can reverse to UTC time this way:

dt = '20230206 04:00:00 Asia/Muscat'
dateTime = dt[0:17]`
timeZone = dt[18:]
dateTimeDt = datetime.strptime(dateTime, "%Y%m%d %H:%M:%S")
timeDiff = datetime.now(pytz.timezone(timeZone)).strftime('%z')
dateTimeUTC = dateTimeDt - timedelta(hours=int(timeDiff)/100)

print('Initial local time : ',dateTime)
print('UTC time: ',dateTimeUTC)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.