How to parse str(my_datetime) using strptime ?

2020-02-14 03:02发布

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 goes in place of the '???' to see the following result:

>>> from dateutil.parser import parse
>>> parse(date_str) == datetime.strptime('???', date_str)
True

2条回答
劳资没心,怎么记你
2楼-- · 2020-02-14 03:25

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 for microseconds; and
  • Either has nothing or an offset with a colon, which doesn't match %z.

.strptime doesn't have support for optional parts, therefore there isn't a single format parameter that can match all of these possible outputs, and doesn't support the colon in the offset, so some can't be handled at all.

查看更多
等我变得足够好
3楼-- · 2020-02-14 03:37

It is not possible using strptime, as has been explained here.

Upgrade to Python 3.7, and use the datetime.fromisoformat method.

Contributed by Paul Ganssle in issue15873.

查看更多
登录 后发表回答