gpt4 book ai didi

python - Strptime 周错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:21:23 28 4
gpt4 key购买 nike

我正在编写一些脚本,这些脚本需要处理一年中的哪一周。我的输入格式为 YYYYWW,例如 '201435'

在我尝试使用 strptime 期间,出于某种原因,它默认为一年中的第一天。例如:

import datetime
test = '201435'
test = datetime.datetime.strptime(test,'%Y%U')
print(test)

输出

2014-01-01 00:00:00

我不确定为什么要这样做。使用 time 模块或将 %U 替换为 %W 具有完全相同的结果。

最佳答案

阅读 the documentation 中的注释 6 :

When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.

因此,由于您没有指定该周的某一天,因此周数将被忽略,您将获得一年中的第一天。要解决这个问题,请添加一天:

>>> datetime.datetime.strptime('2014350', '%Y%U%w')
# ^ here ^ and here
datetime.datetime(2014, 8, 31, 0, 0)

关于python - Strptime 周错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101274/

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