Python dateutil.parser.parse parses month first, not day

故事扮演 提交于 2020-01-09 19:45:50

问题


I'm using dateutil.parser.parse to format a date from a string. But now it mixes up the month and the day.

I have a string that contains 05.01.2015. After

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)

How can I tell the code that the format is dd.mm.yyyy?

For the record, 25.01.2015 will be parsed as (2015, 1, 25, 0, 0), as expected.


回答1:


Specify 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.




回答2:


You asked, 'How can I tell the code that the format is dd.mm.yyyy?'

Since you have already imported dateutil then most direct answer might be to specify the format of the date string but this is quite ugly code:

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

>>> import arrow
>>> arrow.get(date_string, 'DD.MM.YYYY')
<Arrow [2015-01-05T00:00:00+00:00]>

Although I find the formatting for arrow easier to remember, pendulum uses Python's old formatting system which might save you having to learn arrow's.

>>> import pendulum
>>> pendulum.datetime.strptime(date_string, '%d.%m.%Y')
<Pendulum [2015-01-05T00:00:00+00:00]>


来源:https://stackoverflow.com/questions/27800775/python-dateutil-parser-parse-parses-month-first-not-day

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!