LoginSignup
1
2

More than 5 years have passed since last update.

pythonで3ヶ月前の1日を取得・改

Last updated at Posted at 2018-06-06

2018-06-17追記: ライブラリは使わないという制約のもと書いてます。

だいぶ前に3ヶ月前の1日をdatetime.datetime(today.year, today.month - 3, 1)でいいんじゃないか?と書いたけど、よく考えたら1〜3月が前年に繰り下がらない。どうするか?

ifつかうか。。。


import datetime

today = datetime.datetime.today()

if today.month < 4:
    year = today.year - 1
    month = today.month - 3 + 12
else:
    year = today.year
    month = today.month - 3

three_month_ago = datetime.datetime(year, month, 1)

三項演算子つかえばサラッと書けるか試してみる。


import datetime

today = datetime.datetime.today()

year = today.year - 1 if today.month < 4 else today.year
month = today.month - 9 if today.month < 4 else today.month - 3

three_month_ago = datetime.datetime(year, month, 1)

・・・微妙だな。他に、うまいやり方あるのかな?

1
2
1

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
2