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']

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章