---
slug: "python-get-previous-month-without-dateutil"
title: "Python で、 datetime の Nヶ月前を dateutil を使わずに取得"
description: "datetime の Nヶ月前を、dateutil を使わずに取得する関数です。\n\nRe:dash の Python Data Source で、dateutil が使えなかったため作成"
url: "https://www.ytyng.com/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: "ja"
---

# Python で、 datetime の Nヶ月前を dateutil を使わずに取得

datetime の Nヶ月前を、dateutil を使わずに取得する関数です。

Re:dash の Python Data Source で、dateutil が使えなかったため作成

```python
import datetime


def previous_month(dt, delta_months=1):
    """
    datetime の n 月前を取得。

    普通は dateutil を使うが、dateutil の使えない環境で行うコード
    """
    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))
```

### 結果
```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
```

## 追記 Redash では再帰コールができなかったので修正
```python
def previous_month(dt, delta_months=1):
    """
    datetime の n 月前を取得。

    普通は dateutil を使うが、dateutil の使えない環境で行うコード
    """
    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
```
