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)