python 判断两个时间的月份差

#! /usr/bin/env python
# -*- coding:utf-8 -*-

from datetime import datetime,timedelta
import time

#import datetime
import arrow

a='target_display_price_20180701.xlsx'
a_date = ['201807', '201808', '201809', '201810', '201811', '201812', '201901', '201902', '201903', '201904', '201905', '201906']
a_date1 = []
#计算月份两个年月的月份差值
#1.将两个str型的时间转换为datetime型:
start_date = datetime.strptime(a[-13:-7], "%Y%m")
end_date = datetime.strptime(a_date[-1], "%Y%m")
print '时间为%s,%s'%(start_date,end_date)
#2.使用Arrow 对象
def months(str1,str2):
    year1=str1.year
    year2=str2.year
    month1=str1.month
    month2=str2.month
    num=(year1-year2)*12+(month1-month2)
    return num
print months(end_date,start_date)
bb=arrow.get(str(start_date), 'YYYY-MM-DD HH:mm:ss')

for x in range(0,months(end_date,start_date)+1):
    a_date1.append(bb.shift(months=+x).format("YYYYMM"))
print a_date1

 

运行结果:
时间为2018-07-01 00:00:00,2019-06-01 00:00:00
11
[u'201807', u'201808', u'201809', u'201810', u'201811', u'201812', u'201901', u'201902', u'201903', u'201904', u'201905', u'201906']

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值