datetime模块是一个很强大的模块,使用也很方便,在这里简单使用该模块计算指定日期之间的间隔天数已经日期后移或者前推指定周数或者天数的新日期,下面是具体的实现,只是为了学习使用,欢迎交流:
#!usr/bin/env python
#encoding:utf-8
'''
__Author__:沂水寒城
功能:日期计算
'''
import datetime
def cal_two_date_delta_days(one_date,two_date):
'''
计算两个日期之间的天数
'''
year1,month1,day1=[int(one) for one in one_date.split('/')]
year2,month2,day2=[int(one) for one in two_date.split('/')]
one=datetime.date(year1,month1,day1)
two=datetime.date(year2,month2,day2)
delta=str(abs(two-one)).split(',')[0]
msg='{0}和{1}之间相隔{2}'.format(one_date,two_date,delta)
return msg
def cal_specific_date_week(one_date):
'''
计算指定日期是第几周
'''
year1,month1,day1=[int(one) for one in one_date.split('/')]
tmp=datetime.date(year1,month1,day1)
info=list(tmp.isocalendar())
msg='{0}是第{1}周周{2}'.format(one_date,info[1],info[-1])
return msg
def cal_specific_date_after_weeks_date(one_date,n_weeks=100):
'''
计算指定日期后n_weeks周后是某年某月某日
'''
year1,month1,day1=[int(one) for one in one_date.split('/')]
tmp=datetime.date(year1,month1,day1)
delta=datetime.timedelta(weeks=n_weeks)
new_date=(tmp+delta).strftime("%Y-%m-%d %H:%M:%S").split(' ')[0]
msg='{0}过{1}周后日期为:{2}'.format(one_date,n_weeks,new_date)
return msg
def cal_specific_date_after_days_date(one_date,n_days=100):
'''
计算指定日期后n_days天后是某年某月某日
'''
year1,month1,day1=[int(one) for one in one_date.split('/')]
tmp=datetime.date(year1,month1,day1)
delta=datetime.timedelta(days=n_days)
new_date=(tmp+delta).strftime("%Y-%m-%d %H:%M:%S").split(' ')[0]
msg='{0}过{1}天后日期为:{2}'.format(one_date,n_days,new_date)
return msg
if __name__ == '__main__':
date_list=[['2015/09/21','2017/12/18'],['2011/01/21','2016/06/21'],['2014/01/21','2012/3/08']]
for one_list in date_list:
print '*-'*50
one_date,two_date=one_list
print cal_two_date_delta_days(one_date,two_date)
print cal_specific_date_week(one_date)
print cal_specific_date_after_weeks_date(one_date,n_weeks=100)
print cal_specific_date_after_days_date(one_date,n_days=100)
结果如下:
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
2015/09/21和2017/12/18之间相隔819 days
2015/09/21是第39周周1
2015/09/21过100周后日期为:2017-08-21
2015/09/21过100天后日期为:2015-12-30
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
2011/01/21和2016/06/21之间相隔1978 days
2011/01/21是第3周周5
2011/01/21过100周后日期为:2012-12-21
2011/01/21过100天后日期为:2011-05-01
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
2014/01/21和2012/3/08之间相隔684 days
2014/01/21是第4周周2
2014/01/21过100周后日期为:2015-12-22
2014/01/21过100天后日期为:2014-05-01
[Finished in 0.3s]
感觉挺有意思的。