Why is dateutil.parser returning the incorrect date in python?

50 views Asked by At

I'm working with reading dates in from a spreadsheet, and im using parser to convert the strings to dates. From my understanding, this code should return 2023-09-01 00:00:00

from dateutil.parser import parse

print(parse("September, 2023"))

But the output I get is

2023-09-12 00:00:00

When I change my current computer date from June 12 to June 14, the output is now

2023-09-14 00:00:00

From the documentation I searched it should default to the first of the month so I am very confused.

2

There are 2 answers

0
Barmar On

From the source code

        if default is None:
            default = datetime.datetime.now().replace(hour=0, minute=0,
                                                      second=0, microsecond=0)

So if you don't provide the default keyword, it uses the beginning of the current date as the default. Any unspecified fields of the date come from this default.

Where did you read that it uses the first day of the month?

0
jony-jas On

The parse() function uses a default day of the current date when "September, 2023" is passed.

To make to the first of the month you can do as follows.

from dateutil.parser import parse

print(parse("September 1, 2023"))

upvote makes me happy :)