python中取日期范围

2018-01-13 10:57:49来源:oschina作者:好铁人点击

分享
import datetime
from calendar import monthrange
from dateutil.relativedelta import relativedelta# dateutil为第三方库
# 此时此刻
now = datetime.datetime.now()
# 今天
today = now.date()
# 当前月的开始和结束时刻
start_of_current_month = datetime.datetime(now.year, now.month, 1, 0, 0, 0, 0)
end_of_current_month = datetime.datetime(now.year, now.month, monthrange(now.year, now.month)[1], 23, 59, 59, 999999) # 包含. 也可以用下个月的开始作为本月的结束但不包含# 下i个月的此刻
now_of_future_month = now + relativedelta(months=i)
# 上i个月的此刻
now_of_previous_month = now - relativedelta(months=i)# 计算本周的开始和结束(周一至周日)
start_of_this_week = today - datetime.timedelta(days=today.weekday())
end_of_this_week = start_of_this_week + datetime.timedelta(days=7)
# 计算上周的开始和结束(上周一至上周日)
start_of_last_week = start_of_this_week - datetime.timedelta(days=7)
end_of_last_week = start_of_this_week

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台