Python 如何順利地取得上個月的月份

想要取得上個月的月份卻不知如何下手嗎?
當你開心地把今天減去 31 天卻忘記還有二月嗎?

這篇文章教導你,如何順利地取得上個月的月份

解法

在這裡要介紹 today.replace 給卡住的同學

官方文件說明

Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified.

實作上我們利用了 today.replace 把今天的 改為 1
接著再取得 前一天 的日期

如此一來無論在哪一天,我們都可以順利取得上個月的日期了

範例

1
2
3
4
5
6
7
8
import datetime

today = datetime.datetime.today()

first = today.replace(day=1)

last_month = first - datetime.timedelta(days=1)
last_month = last_month.strftime("%Y-%m")

完成 😊

相關文章