Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@yasubei

# 【Python】relativedeltaの月マタギをテストする

More than 1 year has passed since last update.

relativedeltaのメモ書きです(・ω・)ノシ

3/31 - 1ヶ月でどうなるの？とかいろいろ気になったので試しました。

## ソースコード(Python)

```from datetime import datetime
from dateutil.relativedelta import relativedelta

dt_test1 = datetime(2020,3,31)
dt_test2 = dt_test1 - relativedelta(months=1)
dt_test3 = dt_test2 - relativedelta(months=1)
dt_test4 = dt_test3.replace(day=31)
dt_test5 = dt_test4 + relativedelta(months=1)

print("dt_test1={}, dt_test2={}, dt_test3={}, dt_test4={}, dt_test5={}"
.format(dt_test1, dt_test2, dt_test3, dt_test4, dt_test5))
```

## 出力結果

```dt_test1=2020-03-31 00:00:00, dt_test2=2020-02-29 00:00:00, dt_test3=2020-01-29 00:00:00, dt_test4=2020-01-31 00:00:00, dt_test5=2020-02-29 00:00:00
```

## 解説

dt_test1 最初の時間(うるう年の3/31)
dt_test2 3/31-1ヶ月=2/29 (2/31は存在しないので丸められる)
dt_test3 2/29-1ヶ月=1/29 (末日にはならない)
dt_test4 1/29 → 1/31 にしたかっただけ
dt_test5 1/31+1ヶ月=2/29 (3月にはならない)

## 感想

30日足したいだけのときにはrelativedelta(days=30)使えばいいしね

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away