find start and end date of previous month from current date in python

感情迁移 提交于 2021-02-11 12:47:30

问题


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

If the current date is 03-Feb-2021

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?


回答1:


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

Format if/as needed.




回答2:


first date will always be the 1st

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

imports are

from datetime import datetime, timedelta
from calendar import monthrange

you can add one condition for january so it will take december. If have any problem with that just add comment I will add that too.



来源:https://stackoverflow.com/questions/66026812/find-start-and-end-date-of-previous-month-from-current-date-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!