from datetime import datetime,date,timedelta
from dateutil.relativedelta import relativedelta
##返回兩個日期之間的天數
def dates_between(d1,d2):
return abs((d1-d2).days)
##返回兩個月份之間的月數
def months_between(m1,m2):
return abs(m1.year - m2.year)*12 abs(m1.month - m2.month)
##返回兩個日期之間的所有日期字符串(以英文逗号分隔,包含起止日期)
def get_all_dates_between(d1,d2):
ds=''
for i in range(dates_between(datetime.strptime(str(d1),'%Y%m%d'),datetime.strptime(str(d2),'%Y%m%d')) 1):
ds =(datetime.strptime(str(d1),'%Y%m%d') timedelta(days=(-i if d1>=d2 else i))).strftime("%Y%m%d") ','
return ds[:-1]
##返回兩個月份之間的所有月份字符串(以英文逗号分隔,包含起止月份)
def get_all_months_between(m1,m2):
ms=''
for i in range(months_between(datetime.strptime(str(m1),'%Y%m'),datetime.strptime(str(m2),'%Y%m')) 1):
ms =(datetime.strptime(str(m1),'%Y%m') relativedelta(months=(-i if m1>=m2 else i))).strftime("%Y%m") ','
return ms[:-1]
print(months_between(datetime(2021,2,28), datetime(2021,12,1)))
print(months_between(datetime(2021,12,1), datetime(2021,2,28)))
print(dates_between(datetime(2021,5,1), datetime(2021,6,28)))
print(dates_between(datetime(2021,6,28), datetime(2021,5,1)))
print(get_all_months_between('202102','202112'))
print(get_all_months_between('202112','202102'))
print(get_all_dates_between('20210628','20210501'))
print(get_all_dates_between('20210501','20210628'))
,
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!