2017-09-22 171 views
1

我有不同类型的ISO 8601格式化日期字符串,使用datetime library,我想从这些字符串获得datetime object。输入串的Python ISO 8601日期时间解析

实施例:

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

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

我使用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

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

+1

'datetime'中的解析是有限的。看看模块'dateutil'。 – BoarGules

回答

0

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]> 

的页面,我已经说你提到的链接,“库本身支持RFC 3339的格式,最ISO 8601格式和其他一些常见的格式。如果你传递一个非标准的或更复杂的字符串,这个库将在dateutil解析器上回退。

+0

获得一个'Pendulum'对象(解析后)后,我可以从这个摆对象中获得一个'datetime'对象吗? –

+0

您不需要,因为钟摆从日期时间继承。这是直接替换。除了在一个相当有限的情况下(见https://pendulum.eustace.io/faq/),你可以用datetime做任何事情,你可以用摆锤做更多的事情。只需输入摆锤而不是日期。如果您确实想将实例转换为日期时间,请使用其一个或多个属性,adate.year,adate.month,adate.day等。但这几乎是不必要的。 –