1

How to properly use strptime to convert string data from Google Calendar API to datetime object?

Here are two working cases:

from datetime import datetime, timedelta

obj = datetime.strptime('2018-03-01T12:00:00+01:00', '%Y-%m-%dT%H:%M:%S+01:00')
print(obj)   # 2018-03-01 12:00:00

obj = datetime.strptime('2018-03-01T12:00:00+0100', '%Y-%m-%dT%H:%M:%S%z') 
print(obj)   # 2018-03-01 12:00:00+01:00

And one where I have problem.

obj = datetime.strptime('2018-03-01T12:00:00+01:00', '%Y-%m-%dT%H:%M:%S%z')
print(obj)   # ERROR

Why according to documentation %z does not match +01:00 with colon? But only +0100 without colon?

Is there any way to resolve this problem using datetime?

wokadakow
  • 171
  • 11
  • 1
    I can't explain *why* `datetime` seems to have this inconsistency. But have you considered using `dateutil.parser.parse`? This seems to have all your varieties covered. – jpp Feb 27 '18 at 21:25
  • 1
    It seems to be a duplicate of https://stackoverflow.com/questions/30999230/parsing-timezone-with-colon – Laurent H. Feb 27 '18 at 21:32
  • @wokadakow, I added a solution using `dateutil` to the question linked by @LaurentH. – jpp Feb 27 '18 at 21:37
  • 1
    Possible duplicate of [ISO Time (ISO 8601) in Python?](https://stackoverflow.com/questions/2150739/iso-time-iso-8601-in-python) – ivan_pozdeev Feb 27 '18 at 21:37

0 Answers0