pythondatetimestrftime

Using datetime.strptime with default year as current year


Parsing a date string using datetime.strptime such as:

from datetime import datetime       
datetime.strptime('AUG21  3:26PM', '%b%d  %I:%M%p')

Results in

1900-08-21 15:26:00

How can I write something similar in a Pythonic way so that, when there's no year in the date string, it takes the current year as default (e.g 2013) rather than 1900?

I've checked the documentation of the strftime function and it doesn't have an option to change the default year. Maybe another time library can do so?


Solution

  • Parse the date as you are already doing, and then

    date= date.replace(2013)
    

    This is one of simplest solution with the modules you are using.

    Thinking better about it, you will probably face a problem next Feb 29.

    input= 'Aug21  3:26PM'
    output= datetime.datetime.strptime('2013 '+ input ,'%Y %b%d  %I:%M%p')