0
0

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] 前月を取得する

Posted at

やりたいこと

  • ファイル名に前月をつけたい → 前月を取得したい

ポイント

  • datetimeで現在日付を取得して1か月引けばいい
  • dateutilを使うと簡単らしい

サンプルコード

まずはdateutilをインストール

pip install python-dateutil

今日の日付を取得して、1か月ひいてみる

tesy.py
#今日
today = datetime.date.today()
#先月
sengetsu = today - relativedelta(months=1)
結果
2020-03-09

ファイル名に使いたいのはyyyyMMなのでフォーマット

test.pyを修正
sengetsu = (today - relativedelta(months=1)).strftime('%Y%m')
print(sengetsu)
結果
202003

感想

  • 意外と面倒くさいことがわかった

  •  powershellだと (get-date).AddMonths(-1).ToString('yyyyMM')で1行で終わり

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?