How to convert integer into date object python?
Asked Answered
R

5

43

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?

Rexanna answered 17/3, 2012 at 13:26 Comment(0)
L
47

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

Lustral answered 17/3, 2012 at 13:30 Comment(5)
but what i m recieving is not a string. its an integerRexanna
well that's not hard, you can use str(x) to convert the integer into a string.Kemberlykemble
@peter: ok... thnx for suggestionRexanna
@Uday0119: I added a suggestion how to do it properly even for small years.Ibiza
yes @JonasWielicki... thanx for updated information... that is certainly a great help to me...Rexanna
R
51

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')
Riotous answered 24/6, 2012 at 21:42 Comment(3)
How about a pandas series consisting of similar strings/integers like "20120203"?Bellboy
df['order_date'] = df['order_date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))Inanity
@1dhiman, this is the format I'm using but I find that it still is very slow on large datasets. Is there a way to speed it up further in pandas?Hall
L
47

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

Lustral answered 17/3, 2012 at 13:30 Comment(5)
but what i m recieving is not a string. its an integerRexanna
well that's not hard, you can use str(x) to convert the integer into a string.Kemberlykemble
@peter: ok... thnx for suggestionRexanna
@Uday0119: I added a suggestion how to do it properly even for small years.Ibiza
yes @JonasWielicki... thanx for updated information... that is certainly a great help to me...Rexanna
U
14

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.

Undersheriff answered 7/6, 2016 at 8:39 Comment(1)
I don't know how this works (black magic I suspect) but it works a treat! As it's the only one that actually answers the OP it should be the accepted answer.Beaker
A
7
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
Afterword answered 3/2, 2021 at 2:7 Comment(1)
this was very useful thank you very much!Scree
K
0

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)

Koo answered 21/3, 2023 at 14:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.