python获取本周(上周)本月(上月)开始时间以及结束时间

导包

import time
import datetime

获取当前日期

today = datetime.date.today()

本周的开始以及结束日期

# 开始日期
today - datetime.timedelta(days=today.weekday()+7)
# 结束日期
today - datetime.timedelta(days=today.weekday()+1)

上周的开始日期以及结束日期

# 获取当前日期 
date = datetime.datetime.now()
# 上周开始时间
date-datetime.timedelta(days=date.weekday()+7)
# 上周结束时间
date-datetime.timedelta(days=date.weekday()+1)

本月开始以及结束日期

# 获取当前日期 
date = datetime.datetime.now()
year = date.year
month = date.month
# 开始日期
start = datetime.date(year, month, 1)
#结束日期
if month == 12:
    end = datetime.date(year+1, 1, 1) - datetime.timedelta(days=1)
else:
    end = datetime.date(year, month+1, 1) - datetime.timedelta(days=1)

上个月的开始以及结束日期

# 获取当前日期 
date = datetime.datetime.now()
year = date.year
month = date.month
if month == 1:
    start = datetime.date(year-1, 12, 1)
else:
    start = datetime.date(year, month-1, 1)
end = datetime.date(year, month, 1) - datetime.timedelta(days=1)
Last modification:August 8, 2019
If you think my article is useful to you, please feel free to appreciate