Search code examples
pythondatetimestrptime

Strptime Weeks Error


I'm writing some scripts that require manipulating what week of the year it is. My inputs are in the form YYYYWW, such as '201435'.

During my attempts to use strptime it, for some reason, defaults to the first of the year. For example:

import datetime
test = '201435'
test = datetime.datetime.strptime(test,'%Y%U')
print(test)

outputs

2014-01-01 00:00:00

I'm not sure why it's doing so. Using the time module or replacing %U with %W has the exact same result.


Solution

  • Read Note 6 in the documentation:

    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.

    Therefore, as you don't specify a day in that week, the week number is ignored and you get the first of the year. To fix that, add a day:

    >>> datetime.datetime.strptime('2014350', '%Y%U%w')
                                        # ^ here   ^ and here
    datetime.datetime(2014, 8, 31, 0, 0)