python中取日期范围

原创
2018/01/12 14:13
阅读数 718
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

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部