在Python中从当前日期查找上个月的开始和结束日期

f45qwnt8  于 2023-05-19  发布在  Python
关注(0)|答案(3)|浏览(174)

我需要从当前日期查找上个月的开始和结束日期。
如果当前日期为03-Feb-2021
开始日期应为01-Jan-2021,结束日期应为31-Jan-2021
如何实现这一点,因为每个月都有不同天数?我们在datetime中是否有任何函数来实现这一点?

bqujaahr

bqujaahr1#

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

根据需要格式化。

vcudknz3

vcudknz32#

import datetime
from dateutil.relativedelta import relativedelta

# Get current date
today = datetime.date.today()

# Get first day of previous month
first_day = today.replace(day=1) - relativedelta(months=1)

# Get last day of previous month
last_day = today.replace(day=1) - datetime.timedelta(days=1)

# Format dates
start = first_day.strftime('%d-%b-%Y')
end = last_day.strftime('%d-%b-%Y')

# Print dates
print("Start date:", start)
print("End date:", end)
smtd7mpg

smtd7mpg3#

第一次约会永远是第一次

# month_date = (datetime.now() - timedelta(days=20))
month_date = datetime.now().replace(day= monthrange(month_date.year,month_date.month - 1)[1]).strftime("%Y/%m/%d")
start_date = month_date.strftime("%Y/%m/01")
end_date = month_date.replace(day= monthrange(month_date.year,month_date.month)[1]).strftime("%Y/%m/%d")

进口是

from datetime import datetime, timedelta
from calendar import monthrange

你可以在一月份加上一个条件所以要在十二月份。如果有任何问题,只是添加评论,我也会添加。

相关问题