1
datetime.datetime.strptime('2015.18', "%Y.%W")
datetime.datetime(2015, 1, 1, 0, 0)

Whats wrong with my code? 2015 is Year and 18 is the calendar week?

output is completely wrong. Thank you!

noob
  • 111
  • 5
  • 1
    Does this answer your question? [Get date from week number](https://stackoverflow.com/questions/17087314/get-date-from-week-number) – tomgalpin Mar 18 '20 at 14:12

1 Answers1

1

You have to add week day as well to get the desired output.

Following line should work, where 1 is the first day of week.

>>> datetime.datetime.strptime('2015.18.1', "%Y.%U.%w")
datetime.datetime(2015, 5, 4, 0, 0)

Here Sunday is assumed as the first day of the week by python because we are using %U. To set Monday as first day of week use %W or refer to documentation here https://docs.python.org/2/library/datetime.html

Prakhar Patidar
  • 124
  • 1
  • 8
  • hello. thank you. so it isnt possible just to work with the format i have: 2015.18, 2015.19 etc. ? – noob Mar 18 '20 at 14:15
  • "18" would be the 18th calendar week – noob Mar 18 '20 at 14:15
  • 1
    @noob I was also wondering the same. here is some text from Python documentation `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` So I think when we say 18 as the week number but didn't specify any week day it couldn't resolve to a particular date of the year. Thus returning the default date to 1st january of the given year. – Prakhar Patidar Mar 18 '20 at 14:23
  • 1
    Here is the link for the detailed docs of this method (https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) – Prakhar Patidar Mar 18 '20 at 14:28