1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-02-16

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
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?