Python获取上个月的月初和月末日期

在日常数据分析和报表生成的过程中,经常会遇到需要获取上个月的月初和月末日期的需求。Python作为一种功能强大的编程语言,提供了多种方法来实现这一功能。在本文中,我们将介绍如何使用Python来获取上个月的月初和月末日期。

获取上个月的月初日期

要获取上个月的月初日期,我们首先需要导入datetime模块,并利用datetime.date.today()函数获取当前日期。然后,通过计算当前日期的年和月份,即可得到上个月的年和月份。最后,将上个月的年和月份拼接成字符串,并添加上"-01"即可得到上个月的月初日期。

import datetime

today = datetime.date.today()
last_month = today.replace(month=today.month-1, year=today.year if today.month > 1 else today.year-1)

first_day_of_last_month = last_month.replace(day=1)

print("上个月的月初日期为:", first_day_of_last_month)

运行以上代码,即可输出上个月的月初日期。

获取上个月的月末日期

获取上个月的月末日期与获取月初日期类似,只需要将月初日期的1改为上个月的天数即可。Python中提供了calendar模块来获取月份的天数,我们可以借助这个模块来实现获取上个月的月末日期。

import datetime
import calendar

today = datetime.date.today()
last_month = today.replace(month=today.month-1, year=today.year if today.month > 1 else today.year-1)

last_day_of_last_month = last_month.replace(day=calendar.monthrange(last_month.year, last_month.month)[1])

print("上个月的月末日期为:", last_day_of_last_month)

运行以上代码,即可输出上个月的月末日期。

通过以上代码示例,我们可以轻松地获取上个月的月初和月末日期,为数据分析和报表生成提供了便利。在实际应用中,我们可以根据这些日期来进行数据筛选、统计和分析工作,提高工作效率和准确性。

希望本文对您有所帮助,谢谢阅读!

参考链接

  • Python datetime模块文档: [
  • Python calendar模块文档: [