Python datetime.strptime month specifier doesn't seem to work

后端 未结 3 1096
北海茫月
北海茫月 2020-12-21 08:17

The month format specifier doesn\'t seem to work.

from datetime import datetime
endDate = datetime.strptime(\'10 3 2011\', \'%j %m %Y\')
print endDate
2011-0         


        
相关标签:
3条回答
  • 2020-12-21 08:55

    %j specifies a day of the year. It's impossible for the 10th day of the year, January 10, to occur in March, so your month specification is being ignored. Garbage In, Garbage Out.

    0 讨论(0)
  • 2020-12-21 09:06

    You can't mix the %j with others format code like %m because if you look in the table that you linked %j is the Day of the year as a decimal number [001,366] so 10 correspondent to the 10 day of the year so it's 01 of January ...

    So you have just to write :

    >>> datetime.strptime('10 2011', '%j %Y')
    datetime.datetime(2011, 1, 10, 0, 0)
    

    Else if you you wanted to use 10 as the day of the mount you should do :

    >>> datetime.strptime('10 3 2011', '%d %m %Y')
    datetime.datetime(2011, 3, 10, 0, 0)
    
    0 讨论(0)
  • 2020-12-21 09:08

    Isn't %j the "day of year" parser, which may be forcing strptime to choose January 21, overriding the %m rule?

    0 讨论(0)
提交回复
热议问题