Obtaining N Months Ago in Python's datetime Without Using dateutil

2022-11-04 17:25 (2 years ago) ytyng

Here is the English translation of the provided Japanese blog article:


Function to Get N Months Ago in datetime Without Using dateutil

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

Results

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

Addendum: Modified Because Recursive Call Was Not Possible in Redash

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
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011