4

I have the datetime string 2020-10-23T11:50:19+00:00. I can parse it without the timezone as:

>>> datetime.strptime('2020-10-23T11:50:19', '%Y-%m-%dT%H:%M:%S')
datetime.datetime(2020, 10, 23, 11, 50, 19)

But I'm having trouble parsing it with the 00:00 version of the timezone. What would be the correct way to do that?

>>> datetime.strptime('2020-10-23T11:50:19+00:00', '%Y-%m-%dT%H:%M:%S+???')
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

10

You're looking for %z:

>>> datetime.strptime('2020-10-23T11:50:19+00:00', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)

Beware of some Python version compatibility notes:

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

More robust approach, it's not strptime, but it's still in stdlib since Python 3.7:

>>> datetime.fromisoformat('2020-10-23T11:50:19+00:00')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)

As documented this function supports strings in the format:

YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character (not just a T).

wim
  • 338,267
  • 99
  • 616
  • 750
2

The dateutil.parser function will parse that timezone format:

from dateutil.parser import parse

dt = parse('2020-10-23T11:50:19+00:00')
print(dt.date())
print(dt.time())
print(dt.tzinfo)

Result:

2020-10-23
11:50:19
tzutc()

You can combine the separate date, time and tzinfo objects into a datetime, if that's what you need, like this:

dt = datetime.combine(dt.date(), dt.time(), tzinfo=dt.tzinfo)
print(dt)

Result:

2020-10-23 11:50:19+00:00
CryptoFool
  • 21,719
  • 5
  • 26
  • 44