Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...