44

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?

5 Answers 5

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')
Sign up to request clarification or add additional context in comments.

4 Comments

How about a pandas series consisting of similar strings/integers like "20120203"?
df['order_date'] = df['order_date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))
@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?
This actually does not answer the original question.
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

6 Comments

but what i m recieving is not a string. its an integer
well that's not hard, you can use str(x) to convert the integer into a string.
@peter: ok... thnx for suggestion
@Uday0119: I added a suggestion how to do it properly even for small years.
yes @JonasWielicki... thanx for updated information... that is certainly a great help to me...
|
15

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.

1 Comment

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.