Python dateutil.parser.parse 首先解析月,而不是日
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27800775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python dateutil.parser.parse parses month first, not day
提问by Timo002
I'm using dateutil.parser.parse
to format a date from a string. But now it mixes up the month and the day.
我正在使用dateutil.parser.parse
从字符串格式化日期。但现在它混淆了月份和日期。
I have a string that contains 05.01.2015
. After
我有一个包含05.01.2015
. 后
dateutil.parser.parse("05.01.2015")
it returns:
它返回:
datetime.datetime(2015, 5, 1, 0, 0)
I hoped the it would return (2015, 1, 5, 0, 0)
我希望它会回来 (2015, 1, 5, 0, 0)
How can I tell the code that the format is dd.mm.yyyy
?
我怎么能告诉代码格式是dd.mm.yyyy
什么?
For the record, 25.01.2015
will be parsed as (2015, 1, 25, 0, 0)
, as expected.
作为记录,25.01.2015
将按(2015, 1, 25, 0, 0)
预期解析为。
采纳答案by Alex Riley
Specify dayfirst=True
:
指定dayfirst=True
:
>>> dateutil.parser.parse("05.01.2015", dayfirst=True)
datetime.datetime(2015, 1, 5, 0, 0)
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.
在日期格式不明确的情况下(例如,当日为 12 或更低时),这将优先考虑 DD-MM-YYYY 格式而不是 MM-DD-YYYY。该函数记录在此处。
回答by Bill Bell
You asked, 'How can I tell the code that the format is dd.mm.yyyy?'
你问,“我怎么能告诉代码格式是 dd.mm.yyyy?”
Since you have already imported dateutil
then most directanswer might be to specify the format of the date string but this is quite ugly code:
由于您已经导入,dateutil
因此最直接的答案可能是指定日期字符串的格式,但这是非常难看的代码:
>>> dateutil.parser.datetime.datetime.strptime(date_string, '%d.%m.%Y')
datetime.datetime(2015, 1, 5, 0, 0)
We can see an obvious alternative embedded in the code. You could use that directly.
我们可以看到代码中嵌入了一个明显的替代方案。你可以直接使用它。
>>> from datetime import datetime
>>> datetime.strptime(date_string, '%d.%m.%Y')
datetime.datetime(2015, 1, 5, 0, 0)
There are also some newer alternative libraries that offer methods and properties aplenty.
还有一些较新的替代库提供了大量的方法和属性。
Simplest to use in this case would be arrow
:
在这种情况下最简单的使用是arrow
:
>>> import arrow
>>> arrow.get(date_string, 'DD.MM.YYYY')
<Arrow [2015-01-05T00:00:00+00:00]>
Although I find the formatting for arroweasier to remember, pendulumuses Python's old formatting system which might save you having to learn arrow's.
虽然我发现箭头的格式更容易记住,但pendulum使用 Python 的旧格式系统,这可能会让您不必学习箭头的格式。
>>> import pendulum
>>> pendulum.datetime.strptime(date_string, '%d.%m.%Y')
<Pendulum [2015-01-05T00:00:00+00:00]>