数码资讯
python获取上月、当月、下月的开始和结束日期
选购提示
关注价格、性能、续航、售后和真实使用场景,理性比较后再下单。
获取上月开始结束日期
方法一
import datetime
def get_date_of_last_month():
"""
获取上月开始结束日期
:return: str,date tuple
"""
today = datetime.date.today()
days_count = datetime.timedelta(today.day)
end_date = today - days_count
year_month = end_date.strftime("%Y-%m")
begin_of_last_month = f"{year_month}-01"
end_of_last_month = end_date.strftime("%Y-%m-%d")
return begin_of_last_month, end_of_last_month
方法二
import datetime
import calendar
def get_date_of_last_month():
"""
获取上月开始结束日期
:return: str,date tuple
"""
today = datetime.date.today()
today = datetime.date(2022, 1, 1)
year = today.year
month = today.month
if month == 1:
year -= 1
month = 12
else:
month -= 1
begin_of_last_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')
_, day = calendar.monthrange(year, month)
end_of_last_month = datetime.date(year, month, day).strftime('%Y-%m-%d')
return begin_of_last_month, end_of_last_month
方法三
import datetime
def get_date_of_last_month():
"""
获取上月开始结束日期
:return: str,date tuple
"""
today = datetime.date.today()
year = today.year
month = today.month
if month == 1:
begin_of_last_month = datetime.date(year - 1, 12, 1).strftime('%Y-%m-%d')
else:
begin_of_last_month = datetime.date(year, month - 1, 1).strftime('%Y-%m-%d')
end_of_last_month = (datetime.date(year, month, 1) + datetime.timedelta(-1)).strftime('%Y-%m-%d')
return begin_of_last_month, end_of_last_month
获取当月开始结束日期
import datetime
import calendar
def get_date_of_month():
"""
获取当月开始结束日期
:return: str,date tuple
"""
today = datetime.date.today()
year = today.year
month = today.month
begin_of_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')
_, day = calendar.monthrange(year, month)
end_of_month = datetime.date(year, month, day).strftime('%Y-%m-%d')
return begin_of_month, end_of_month
获取下月开始结束日期
import datetime
import calendar
def get_date_of_next_month():
"""
获取下月开始结束日期
:return: str,date tuple
"""
today = datetime.date.today()
year = today.year
month = today.month
if month == 12:
year += 1
month = 1
else:
month += 1
begin_of_next_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')
_, day = calendar.monthrange(year, month)
end_of_next_month = datetime.date(year, month, day).strftime('%Y-%m-%d')
return begin_of_next_month, end_of_next_month
声明:本文内容用于数码产品信息整理与选购参考,具体价格、库存、售后政策以官方渠道和电商页面实时信息为准。