Python ISO 8601 日期时间解析

Python ISO 8601 datetime parsing

我有不同类型的 ISO 8601 格式化日期字符串,使用 datetime library,我想从这些字符串中获得 datetime object

输入字符串示例:

  1. 2017-08-01(2017 年 8 月 1 日)
  2. 2017-09(2017 年 9 月)
  3. 2017-W20(第 20 周)
  4. 2017-W37-2(第 37 周星期二)

我能够获得第一个、第二个和第四个示例,但是对于第三个示例,我在尝试时得到了回溯。

我在 try-except 块中为它们使用 datetime.datetime.strptime 函数,如下所示:

try :
    d1 = datetime.datetime.strptime(date,'%Y-%m-%d')
except :
    try :
        d1 = datetime.datetime.strptime(date,'%Y-%m')
    except :
        try :
            d1 = datetime.datetime.strptime(date,'%G-W%V')
        except :
            print('Not going through')

当我在终端上尝试第三个 try 块时,这是我得到的错误

>>> dstr
'2017-W38'
>>> dt.strptime(dstr,'%G-W%V')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 483, in _strptime
    raise ValueError("ISO year directive '%G' must be used with "
ValueError: ISO year directive '%G' must be used with the ISO week directive '%V' and a weekday directive ('%A', '%a', '%w', or '%u').

这就是我如何让第 4 个案例工作的:

>>> dstr
'2017-W38-2'
>>> dt.strptime(dstr,'%G-W%V-%u')
datetime.datetime(2017, 9, 19, 0, 0)

这是我的代码的参考:strptime documentation

SO 上有很多关于从 ISO 8601 格式解析日期的问题,但我找不到解决我的问题的问题。此外,所涉及的问题非常古老,采用旧版本的 python,其中 %G%V 指令在 strptime 中不可用。

pendulum 库在这些方面做得很好。

>>> import pendulum
>>> pendulum.parse('2017-08-01')
<Pendulum [2017-08-01T00:00:00+00:00]>
>>> pendulum.parse('2017-09')
<Pendulum [2017-09-01T00:00:00+00:00]>
>>> pendulum.parse('2017-W20')
<Pendulum [2017-05-15T00:00:00+00:00]>
>>> pendulum.parse('2017-W37-2')
<Pendulum [2017-09-12T00:00:00+00:00]>

我在 link 中向您推荐的页面说,'The library natively supports the RFC 3339 format, most ISO 8601 formats and some other common formats. If you pass a non-standard or more complicated string, the library will fallback on the dateutil parser.'