Strptime 周错误

Strptime Weeks Error

我正在编写一些脚本,这些脚本需要处理一年中的哪一周。 我的输入格式为 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)