tompal18
tompal18

Reputation: 1216

first week number to date prints previous year

I want follow code to print 2020-01-01 00:00:00 instead of 2019-12-30.

Any help would be appreciated.

d = '2020-00'
r = datetime.datetime.strptime(d + '-1', "%Y-%W-%w")
print(r)
2019-12-30 00:00:00

Upvotes: 1

Views: 37

Answers (1)

MattDMo
MattDMo

Reputation: 102852

2020 started on a Wednesday. From this handy Python str[fp]time reference, %W stands for

Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.

while %w is

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

You passed the value 2020-00-1, which corresponds to the 0th week's Monday, which was in fact 2019-12-30.

To make it result in 2020-01-01, do the following:

>>> import datetime
>>> d = "2020-00"
>>> r = datetime.datetime.strptime(d + "-3", "%Y-%W-%w")
>>> print(r)
2020-01-01 00:00:00

Upvotes: 1

Related Questions