gpt4 book ai didi

python - 通过仅提供月份或仅提供星期几来创建日期时间对象

转载 作者:行者123 更新时间:2023-12-05 06:05:03 25 4
gpt4 key购买 nike

通过仅提供月份在 Python 中创建一个 datetime 对象会保留月份信息:

>>> import datetime
>>> datetime.datetime.strptime('Feb', '%b')
datetime.datetime(1900, 2, 1, 0, 0)
>>> datetime.datetime.strptime('Feb', '%b').strftime('%B')
'February'

由于未提供年份或日期,Python 分别使用默认值 1900 和 01,结果为 datetime.datetime(1900, 2, 1, 0, 0)

但是,如果提供了星期几:

>>> datetime.datetime.strptime('Tue', '%a')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.datetime.strptime('Tue', '%a').strftime('%A')
'Monday'

我知道 1900-01-01 是星期一,但为什么 Python 不创建对象 datetime.datetime(1900, 1, 2, 0, 0) 这是 1900-01-01 之后的第一个星期二,类似于第一个示例中二月的情况?

似乎初始信息(即当天是星期二)在没有任何警告或错误的情况下丢失了。通过仅提供月份和仅提供星期几来创建 datetime 对象之间是否存在根本区别?

最佳答案

根据 docs :

For the datetime.strptime() class method, the default value is 1900-01-01T00:00:00.000: any components not specified in the format string will be pulled from the default value.

重要的部分:

Similar to %U and %W, %V is only used in calculations when the day ofthe week and the ISO year (%G) are specified in a strptime() formatstring. Also note that %G and %Y are not interchangeable.

我猜 %a 属于相同的条件,但没有在文档中指定。

您可以将 %G(ISO 8601 年)与 %V(ISO 8601 周)与 %a 一起使用,那么它应该工作:

>>> datetime.datetime.strptime('1900 01 Tue', '%G %V %a').strftime('%Y-%m-%d %a')
'1900-01-02 Tue'

>>> datetime.datetime.strptime('1900 02 Tue', '%G %V %a').strftime('%Y-%m-%d %a')
'1900-01-09 Tue'

我相信这是因为您可以通过这种方式指定所需的星期。

关于python - 通过仅提供月份或仅提供星期几来创建日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66107593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com