datetime library
を使用してISO 8601
の書式設定された日付文字列が異なるタイプがあります。これらの文字列からdatetime object
を取得します。Python ISO 8601日時解析
入力文字列の例:
2017-08-01
(2017年8月1日)2017-09
(2017年の9月)2017-W20
(20週)2017-W37-2
(第37週の火曜日)
私は第1、第2、第4エキスを得ることができましたmples。しかし、3回目は、試している間にトレースバックを取得する。次のように私は、ブロック-以外の試みを彼らのために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').
を得たエラーです
そして、これは私が第四ケースの作業を得た方法である:ここでは
>>> dstr
'2017-W38-2'
>>> dt.strptime(dstr,'%G-W%V-%u')
datetime.datetime(2017, 9, 19, 0, 0)
は参照です私のコードのために:strptime documentation
はSO ISO 8601
形式から解析した日付についての多くの質問がありますが、私は私の問題に対処するものを見つけることができませんでした。さらに、関連する質問は非常に古いもので、%G
、%V
の指示文がstrptime
に存在しないPythonの古いバージョンを使用しています。
'datetime'の解析には制限があります。モジュール 'dateutil'を見てください。 – BoarGules