How to convert integer into date object python?

前端 未结 3 2027
无人共我
无人共我 2020-12-03 01:15

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 conver

3条回答
  •  时光说笑
    2020-12-03 01:52

    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

提交回复
热议问题