Search code examples
pythondatetimedatetime-format

Datetime from year and week number


I have a year and a week number which I want to convert into a datetime.datetiem object. My (naive?) reading of the documentation hinted that strptime('2016 00', '%Y %W') should do just that. However:

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)

What am I doing wrong?


Solution

  • So it turns out that the week number isn't enough for strptime to get the date. Add a default day of the week to your string so it will work.

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

    The 0 tells it to pick the Sunday of that week, but you can change that in the range of 0 through 6 for each day.