来自年份和周数的日期时间

Datetime from year and week number

我有一个年份和一个星期的数字,我想将其转换为 datetime.datetiem 对象。我(天真?)对文档的阅读暗示 strptime('2016 00', '%Y %W') 应该做到这一点。然而:

In [2]: from datetime import datetime

In [3]: datetime.strptime('2016 00', '%Y %W')
Out[3]: datetime(2016, 1, 1, 0, 0)

In [4]: datetime.strptime('2016 52', '%Y %W')
Out[4]: datetime(2016, 1, 1, 0, 0)

我做错了什么?

来自docs(见底部注释7):

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.strptime('2016', '%Y') 相同的结果。

所以事实证明周数不足以 strptime 获取日期。将默认的星期几添加到您的字符串中,这样它就可以工作了。

> from datetime import datetime
> myDate = "2016 51"
> datetime.strptime(myDate + ' 0', "%Y %W %w")
> datetime.datetime(2016, 12, 25, 0, 0)

0 告诉它选择那一周的星期日,但您可以在 0 到 6 的范围内为每一天更改它。