How to convert integer into date object python? How to convert integer into date object python? python python

How to convert integer into date object python?


I would suggest the following simple approach for conversion:

from datetime import datetime, timedeltas = "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


This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.

import datetimes = "20120213"s_datetime = datetime.datetime.strptime(s, '%Y%m%d')


Here is what I believe answers the question (Python 3, with type hints):

from datetime import datedef int2date(argdate: int) -> date:    """    If you have date as an integer, use this method to obtain a datetime.date object.    Parameters    ----------    argdate : int      Date as a regular integer value (example: 20160618)    Returns    -------    dateandtime.date      A date object which corresponds to the given value `argdate`.    """    year = int(argdate / 10000)    month = int((argdate % 10000) / 100)    day = int(argdate % 100)    return date(year, month, day)print(int2date(20160618))

The code above produces the expected 2016-06-18.