dateutil.parser在Python中返回错误的日期的原因是什么?

huangapple go评论55阅读模式
英文:

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

问题

我正在处理从电子表格中读取的日期,并使用解析器将字符串转换为日期。根据我的理解,这段代码应该返回2023年09月01日 00:00:00

from dateutil.parser import parse

print(parse("September, 2023"))

但我得到的输出是

2023-09-12 00:00:00

当我将当前计算机的日期从6月12日更改为6月14日时,输出变为

2023-09-14 00:00:00

根据我搜索到的文档,它应该默认为每月的第一天,所以我感到非常困惑。

英文:

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.

答案1

得分: 1

如果未提供`default`关键字则会将当前日期的开始作为默认值日期的任何未指定字段都将来自此默认值
英文:

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?

答案2

得分: 0

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

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

from dateutil.parser import parse

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

upvote makes me happy dateutil.parser在Python中返回错误的日期的原因是什么?

英文:

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"))

<sub>upvote makes me happy :)</sub>

huangapple
  • 本文由 发表于 2023年6月13日 00:40:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定