---
slug: "python-get-previous-month-without-dateutil"
title: "Obtaining N Months Ago in Python's datetime Without Using dateutil"
description: "Here's an overview of the blog post in English:\n\n---\n\nThis blog post introduces a function to obtain a datetime N months ago, without using the `dateutil` library.\n\nThe function was created because `dateutil` was not available in the Python Data Source for Re:dash.\n\n---"
url: "https://www.ytyng.com/en/blog/python-get-previous-month-without-dateutil"
publish_date: "2022-11-04T08:25:34Z"
created: "2022-11-04T08:25:34Z"
updated: "2026-02-27T10:41:51.114Z"
categories: []
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20250711/1e3808e1a8014520a8dab2e7bd1f1040.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

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

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.

```python
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
```text
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
```python
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
```
