Help us understand the problem. What is going on with this article?

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

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)使えばいいしね

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした