我有不同類型的ISO 8601
格式化日期字符串,使用datetime library
,我想從這些字符串獲得datetime object
。輸入串的Python ISO 8601日期時間解析
實施例:
2017-08-01
(2017年8月1日)2017-09
(2017九月)2017-W20
(第20周)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
不可用。
'datetime'中的解析是有限的。看看模塊'dateutil'。 – BoarGules