0
Help us understand the problem. What are the problem?

posted at

1年前の日付を求める

1年前の日付とググるとdateutilのrelativedelta()を使う旨がよく出てくる。
一目datetimeでマイナス365日で良さそうだがうるう年を考慮するとrelativedelta()が良いようだ。

日付 timedelta(days=365) relativedelta(years=1) 備考
2020/2/28 2019/02/28 2019-02-28 期待通り
2020/2/29 2019/03/01 2019-02-28 うるう年はずれる
2020/3/01 2019/03/02 2019-03-01 同上

// 2020/2/28 の365日前
$ python3 -c "import datetime; print(datetime.date(2020,2,28) - datetime.timedelta(days=365))"
2019-02-28

// 2020/2/28 の一年前
$ python3 -c "import datetime, dateutil.relativedelta; print(datetime.date(2020,2,28) - dateutil.relativedelta.relativedelta(years=1))"
2019-02-28

// 2020/2/29 の365日前
$ python3 -c "import datetime; print(datetime.date(2020,2,29) - datetime.timedelta(days=365))"
2019-03-01

// 2020/2/29 の一年前
$ python3 -c "import datetime, dateutil.relativedelta; print(datetime.date(2020,2,29) - dateutil.relativedelta.relativedelta(years=1))"
2019-02-28

// 2020/2/29 の365日前
$ python3 -c "import datetime; print(datetime.date(2020,3,1) - datetime.timedelta(days=365))"
2019-03-02

// 2020/2/29 の一年前
$ python3 -c "import datetime, dateutil.relativedelta; print(datetime.date(2020,3,1) - dateutil.relativedelta.relativedelta(years=1))"
2019-03-01

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?