It is a memo of relative delta (・ ω ・) Noshi
3/31 --What happens in a month? I was curious about things like that, so I tried it.
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
variable | What I wanted to try & results |
---|---|
dt_test1 | First time(Leap year 3/31) |
dt_test2 | 3/31-1 month=2/29 (2/31 does not exist so it can be rounded) |
dt_test3 | 2/29-1 month=1/29 (It will not be the last day) |
dt_test4 | 1/29 → 1/I just wanted to be 31 |
dt_test5 | 1/31+1 month=2/29 (It won't be March) |
I thought it would be convenient because it works intuitively for the purpose I want to use (・ ω ・) If you just want to add 30 days, you can use relative delta (days = 30).
Recommended Posts