pythonpython-2.7datepython-datetimestrptime

How to convert integer into date object python?


I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.

Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?


Solution

  • I would suggest the following simple approach for conversion:

    from datetime import datetime, timedelta
    s = "20120213"
    # you could also import date instead of datetime and use that.
    date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
    

    For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

    date += timedelta(days=10)
    date -= timedelta(days=5)
    

    And convert back using:

    s = date.strftime("%Y%m%d")
    

    To convert the integer to a string safely, use:

    s = "{0:-08d}".format(i)
    

    This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

    Further reference: datetime objects, timedelta objects