問題描述
我正在使用 dateutil.parser.parse
從字符串格式化日期.但現(xiàn)在它混淆了月份和日期.
I'm using dateutil.parser.parse
to format a date from a string. But now it mixes up the month and the day.
我有一個包含 05.01.2015
的字符串.之后
I have a string that contains 05.01.2015
. After
dateutil.parser.parse("05.01.2015")
它返回:
datetime.datetime(2015, 5, 1, 0, 0)
我希望它會返回 (2015, 1, 5, 0, 0)
如何告訴代碼格式是dd.mm.yyyy
?
作為記錄,25.01.2015
將按預(yù)期被解析為 (2015, 1, 25, 0, 0)
.
For the record, 25.01.2015
will be parsed as (2015, 1, 25, 0, 0)
, as expected.
推薦答案
指定dayfirst=True
:
>>> dateutil.parser.parse("05.01.2015", dayfirst=True)
datetime.datetime(2015, 1, 5, 0, 0)
在日期格式不明確的情況下(例如,當(dāng)日期為 12 或更低時),這將優(yōu)先使用 DD-MM-YYYY 格式而不是 MM-DD-YYYY.該函數(shù)記錄在這里.
This gives precedence to the DD-MM-YYYY format instead of MM-DD-YYYY in cases where the date format is ambiguous (e.g. when the day is 12 or lower). The function is documented here.
這篇關(guān)于Python dateutil.parser.parse 首先解析月份,而不是日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!