在python中从当前日期查找上个月的开始和结束日期 [英] find start and end date of previous month from current date in python

查看:76
本文介绍了在python中从当前日期查找上个月的开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从当前日期开始查找上个月的开始和结束日期.

I need to find the start and end date of the previous month from the current date.

如果当前日期为 2021年2月3日

开始日期应为 2021年1月1日,结束日期应为 2021年1月31日.

The start date should be 01-Jan-2021 and the end date should be 31-Jan-2021.

如何实现这一目标,因为每个月都有不同的天数?我们在日期时间中有什么功能可以做到这一点?

how to achieve this as each month have a different number of days? Do we have any function in datetime to achieve this?

推荐答案

>>> from datetime import date, timedelta
>>> this_first = date.today().replace(day=1)
>>> prev_last = this_first - timedelta(days=1)
>>> prev_first = prev_last.replace(day=1)
>>> prev_first, prev_last
(datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))

根据需要设置格式.

这篇关于在python中从当前日期查找上个月的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆