Search code examples
pythondatetimepython-datetime

How to convert "1030" to 10-30 in mm-dd date format in Python?


Is there a simple way to convert numbers like 1030, 0131, 1231, etc to an mm-dd (or even mm-dd-yyyy assuming everything is 2020) format, so that I can perform date calculations with them? For example, I would like to be able to do (1231 minus 0131) = 11 months.

Of course, I could just do the following to change the formatting, but looking to see if there's a more intuitive way!

startDate = startDate[:2] + "-" + startDate[2:] + "-2020"
endDate = endDate[:2] + "-" + endDate[2:] + "-2020"

Solution

  • You can convert to datetime object straight away, using strptime directive "%m%d". This allows you to make timedelta calculations later on. The default year is 1900; if you wish, you can replace by 2020.

    from datetime import datetime
    
    startDate, endDate = "0131", "1231"
    
    startDate, endDate = (datetime.strptime(startDate, "%m%d").replace(year=2020), 
                          datetime.strptime(endDate,"%m%d").replace(year=2020))
    
    deltaDays = (endDate-startDate).days
    # 335