python日期之间月份列表

本文共有915个字,关键词:

问题:python如何获取两个日期之间的月份列表

方法:

from datetime import datetime

#这是起始时间,假设某位博主是2018年10月6日注册的
start=datetime(2018,10,6)
#这是结束时间,也就是当前的时间
end=datetime.now()
#计算起止日期之间有多少个月(月份的差值)
month_num=12*(end.year-start.year)+end.month-start.month
#这个空列表用于存储我们最终得出的所有的年月
time_list=[]
#年份的起点是注册日期的年份
year=start.year
#月份的起点是注册日期的月份
month=start.month
#遍历月份数+1,之所以加1是因为即使是本月注册的博主,月份差为0,他的页面也要显示一个月,即本月
for m in range(month_num+1):
    #把年月的小列表追加进大列表
    time_list.append([year,month])
    #月份加1
    month+=1
    #当月份达到13的时候,需要再从1月开始数,而且这代表跨年了,所以年份加1
    if month==13:
        month=1
        year+=1
#我希望最终的结果是当前月份在最前面,离我越远的月份越靠后,所以这里要反转列表
time_list.reverse()
print(time_list)

参考:

https://blog.csdn.net/weixin_44520259/article/details/97656945
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论