1
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】月の初日や最終日を取得する方法

Last updated at Posted at 2020-05-27

結論

replaceメソッドを使うと楽チン。

from datetime import datetime
from dateutil.relativedelta import relativedelta

today = datetime.now().date()
print(today)
# => 2020-05-27

last_month_start = (today - relativedelta(months=1)).replace(day=1)
print(last_month_start)
# => 2020-04-01

last_month_end = today.replace(day=1) - relativedelta(days=1)
print(last_month_end)
# => 2020-04-30

変数名がアレなのは見逃してください。

参考

1
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
1
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?