5

This is the default string representation of a datetime:

>>> from datetime import datetime, timezone
>>> dt = datetime(2017, 1, 1, tzinfo=timezone.utc)
>>> print(dt)
2017-01-01 00:00:00+00:00

What is the correct format string to parse that with datetime.strptime? That is, what format goes in place of the "???" to consistently have the following invariant:

>>> dt == datetime.strptime(str(dt), "???")
True
wim
  • 338,267
  • 99
  • 616
  • 750

1 Answers1

4

Note that str(d) is documented as being equivalent to d.isoformat(' '). This starts with %Y-%m-%d %H:%M:%S (2017-01-01 00:00:00), but then:

  • Either has nothing or .%f, depending whether the microseconds part is nonzero.
  • Either has nothing or an offset like +HH:MM, depending whether the instance is timezone-aware.

datetime.strptime doesn't have support for optional parts, therefore there isn't a single format parameter that can match all of the possible outputs.

In Python 3.7+, you can use datetime.fromisoformat to parse datetime.isoformat output. Contributed by Paul Ganssle in issue15873.

wim
  • 338,267
  • 99
  • 616
  • 750
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    *Note:* one detail has become a little outdated, strptime %z supports colon in the offset now (new in Python 3.7) – wim Oct 23 '20 at 20:38