Here is the English translation of the provided Japanese blog article:
Since dateutil was not available in the Python Data Source of Re:dash, I created this function.
import datetime
def previous_month(dt, delta_months=1):
"""
Get the date n months ago in datetime.
Normally, dateutil would be used, but this code is for environments where dateutil cannot be used.
"""
if delta_months == 0:
return dt
new_dt = datetime.datetime(dt.year, dt.month, 1) \
- datetime.timedelta(days=1)
return previous_month(datetime.datetime(
new_dt.year, new_dt.month, 1), delta_months - 1)
for i in range(13):
print(
f'2022-02-10 - {i} =>',
previous_month(datetime.datetime(2022, 2, 10), i))
2022-02-10 - 0 => 2022-02-10 00:00:00
2022-02-10 - 1 => 2022-01-01 00:00:00
2022-02-10 - 2 => 2021-12-01 00:00:00
2022-02-10 - 3 => 2021-11-01 00:00:00
2022-02-10 - 4 => 2021-10-01 00:00:00
2022-02-10 - 5 => 2021-09-01 00:00:00
2022-02-10 - 6 => 2021-08-01 00:00:00
2022-02-10 - 7 => 2021-07-01 00:00:00
2022-02-10 - 8 => 2021-06-01 00:00:00
2022-02-10 - 9 => 2021-05-01 00:00:00
2022-02-10 - 10 => 2021-04-01 00:00:00
2022-02-10 - 11 => 2021-03-01 00:00:00
2022-02-10 - 12 => 2021-02-01 00:00:00
def previous_month(dt, delta_months=1):
"""
Get the date n months ago in datetime.
Normally, dateutil would be used, but this code is for environments where dateutil cannot be used.
"""
import datetime
new_dt = datetime.datetime(dt.year, dt.month, 1)
for i in range(delta_months):
new_dt = new_dt - datetime.timedelta(days=1)
new_dt = datetime.datetime(new_dt.year, new_dt.month, 1)
return new_dt
Comments