How to convert integer into date object python?

Question:

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?

Asked By: Uday0119

||

Answers:

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

Answered By: Jonas Schäfer

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 in the accepted answer, you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.

import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
Answered By: W.Prins

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

from datetime import date


def 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.

Answered By: DejanLekic
import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00
Answered By: Raghav Mehra

In Python 3.11+ one can use date.fromisoformat for this purpose:

from datetime import date, timedelta

integer_date = 20120213
date_object = date.fromisoformat(f'{integer_date}')
print(f'{date_object - timedelta(30):%Y%m%d}')  # prints 20120114

Changed in version 3.11: Previously, this method only supported the format YYYY-MM-DD.

Performance

A timeit on my machine shows that fromisoformat is around 60 times faster than using datetime class, and about 7 times faster than strptime. Here is the code:

import datetime as dt
from timeit import timeit


strptime = dt.datetime.strptime
fromisoformat = dt.datetime.fromisoformat
datetime = dt.datetime

s = "20120213"
assert datetime(int(s[0:4]), int(s[4:6]), int(s[6:8])) == fromisoformat(s) == strptime(s, '%Y%m%d')

strptime_time = timeit('strptime(s, "%Y%m%d")', globals=globals())
fromisoformat_time = timeit('fromisoformat(s)', globals=globals())
datetime_time = timeit('datetime(int(s[0:4]), int(s[4:6]), int(s[6:8]))', globals=globals())

print(f'{strptime_time/fromisoformat_time=}')
print(f'{datetime_time/fromisoformat_time=}')

Result:

strptime_time/fromisoformat_time=60.46678219698884
datetime_time/fromisoformat_time=7.008299761426674

(Using CPython 3.11.2 and Windows 10)

Answered By: AXO