有时候需要算两个日期相差多少天,如果两个日期相差大,真的去数肯定很麻烦,还得计算有的是有三十天,有的是三十一天,还有闰年和平年的区别。而这时候如果有一个方法或者函数,只需要输入要计算的两个日期即可,那就方便快捷了很多。
而Python正好可以提供这么一个方法函数,为什么选择Python,首先它的体积小,环境配置简单,其次配置了环境变量后,脚本可以像txt,word等一样独立运行。(代码所用的Python版本为Python3.6。)
首先导入需要用到的时间和日期库,创建日期相差的方法函数:
-
import time -
import datetime -
#计算两个日期相差天数,自定义函数名,和两个日期的变量名。 -
def Caltime(date1,date2): -
#%Y-%m-%d为日期格式,其中的-可以用其他代替或者不写,但是要统一,同理后面的时分秒也一样;可以只计算日期,不计算时间。 -
#date1=time.strptime(date1,"%Y-%m-%d %H:%M:%S") -
#date2=time.strptime(date2,"%Y-%m-%d %H:%M:%S") -
date1=time.strptime(date1,"%Y-%m-%d") -
date2=time.strptime(date2,"%Y-%m-%d") -
#根据上面需要计算日期还是日期时间,来确定需要几个数组段。下标0表示年,小标1表示月,依次类推... -
#date1=datetime.datetime(date1[0],date1[1],date1[2],date1[3],date1[4],date1[5]) -
#date2=datetime.datetime(date2[0],date2[1],date2[2],date2[3],date2[4],date2[5]) -
date1=datetime.datetime(date1[0],date1[1],date1[2]) -
date2=datetime.datetime(date2[0],date2[1],date2[2]) -
#返回两个变量相差的值,就是相差天数 -
return date2-date1
接着就是需要判断输入的日期时候为合法日期了,函数代码为:
-
#判断日期是否为合法输入,年月日的格式需要与上面对应,正确返回True,错误返回False,注意大小写。 -
def is_date(str): -
try: -
time.strptime(str,"%Y-%m-%d") -
return True -
except: -
return False
最后就是运用函数,并输出到txt文档中:
-
if __name__=='__main__': -
#提示信息请根据实际情况更改 -
print('请输入较早日期(格式例:xxxx-xx-xx):') -
while True: -
dt1=input() -
if is_date(dt1)==True: -
break -
else: -
print('请输入正确的日期!!!请重新输入!!!') -
#print(is_date(dt1)) -
print('\n请输入较晚日期(格式为:xxxx-xx-xx):') -
while True: -
dt2=input() -
if is_date(dt2)==True: -
break -
else: -
print('请输入正确的日期!!!请重新输入!!!') -
#将结果保存到当前目录下的t_day.txt,该txt文档会自动创建,名字可自定义。 -
with open('./t_day.txt','a') as f: -
f.write('较早日期为:'+dt1+' 较晚日期为:'+dt2) -
f.write('\n两个日期相差 ') -
print (Caltime(dt1,dt2),file=f) -
f.write('\n') -
f.close


有的时候要统计两个日期之间的相距天数,可能有很多种方法,但使用datetime模块的datetime方法无疑是里面比较简单的,具体代码如下:
>>> import datetime
>>> d1 = datetime.datetime(2018,10,31) # 第一个日期
>>> d2 = datetime.datetime(2019,02,02) # 第二个日期
>>> interval = d2 - d1 # 两日期差距
>>> interval.days # 具体的天数
94
>>> interval.seconds # 具体的秒数
0
>>>
从上面来看,还是相当简单。具体的days和seconds就是具体的差距的天数和额外的秒数。里面常用的方法有:
>>> filter(lambda x: not x.startswith("_"), dir(interval))
['days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
>>>
如果是两个日期还是带时,分,秒的话,同样可以算出两者的相距天数及秒数.
>>> import datetime
>>> d1 = datetime.datetime(2018,10,31,10,30,00)
>>> d2 = datetime.datetime(2018,11,01,10,40,30)
>>> interval = d2 - d1
>>> interval # 第一项是天数,相距1天
datetime.timedelta(1, 630)
>>> interval.days # 具体天数
1
>>> interval.seconds # 额外秒数
630
>>> interval.total_seconds() # 相差总秒数
87030.0
>>>
————————————————
原文链接:https://blog.csdn.net/jerry_1126/article/details/83590783

2万+

被折叠的 条评论
为什么被折叠?



