python应用:日期时间
计算时间差时,注意天数差引发的问题,获取天数差为
(date2-date1).days
此处,需谨记date2>date1,以保证结果的正确性
具体应用如下:
1 # -*-coding:utf8-*- 2 # 计算时间差 3 import time 4 import datetime 5 def time_interval(): 6 # 获取当前时间 7 #time_old = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 8 time_old = '2018-1-1 23:40:01' 9 print time_old 10 #time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 11 time_now = '2018-1-2 00:10:01' 12 print time_now 13 old_time = time.strptime(time_old,'%Y-%m-%d %H:%M:%S') 14 now_time = time.strptime(time_now,'%Y-%m-%d %H:%M:%S') 15 #print old_time 16 date1 = datetime.datetime(old_time[0], old_time[1], old_time[2], old_time[3], old_time[4], old_time[5]) 17 date2 = datetime.datetime(now_time[0], now_time[1], now_time[2], now_time[3], now_time[4], now_time[5]) 18 return (date2-date1).seconds 19 20 print time_interval()
注意:strftime()与strptime()的不同