Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 636
I Z Avatar asked Dec 10 '15 14:12

I Z


1 Answers

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.

like image 123
falsetru Avatar answered Nov 15 '22 07:11

falsetru