How can I set day to 1 when parsing incomplete date with dateutil.parser?
Asked Answered
B

1

5

When I use dateutil.parser to parse an incomplete date that's missing the day, I get the day set to 10 for some reason:

from dateutil.parser import parse
>>> d1 = parse('2008 Apr 2')
>>> d1
datetime.datetime(2008, 4, 2, 0, 0)
>>> d2 = parse('2014 Apr')
>>> d2
datetime.datetime(2014, 4, 10, 0, 0)

Is there a way to changing this so that the day gets automatically set to 1 instead for such incomplete cases?

Baguio answered 10/12, 2015 at 14:41 Comment(2)
Is it picking up today's day?Finalize
@JasonHeine That's a great observation, I didn't think of that. But I can't be running my processing only on the 1st of each month :-)Baguio
M
12

You can pass default keyword argument. If the default is specified, parser will replace default's part with parsed date:

>>> import datetime
>>> from dateutil.parser import parse
>>>
>>> print parse('2014 Apr', default=datetime.datetime(2015, 1, 1))
2014-04-01 00:00:00

According to dateutil.parser.parse documentation:

default – The default datetime object, if this is a datetime object and not None, elements specified in timestr replace elements in the default object.

Martz answered 10/12, 2015 at 14:54 Comment(2)
Is there any way to define just a default value to the day? My expectation would be for this case parse("2014 Apr") # 2014-01-01 00:00:00Avantgarde
@vildhjarta, Sorry, I don't know the way.Martz

© 2022 - 2024 — McMap. All rights reserved.