前言
1、在python中經常會用到計算兩個時間差,兩個日期類型進行相減可以擷取到時間差。
2、 seconds 函數擷取的是僅僅是時間差的秒數,忽略微秒數,忽略天數。
3、 total_seconds() 函數是擷取兩個時間之間的總差。
4、 total_seconds() = (td.microseconds+ (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 # td是timedelta對象
執行個體
執行個體1:
#-*- coding: UTF-8 -*-
'''
Created on 2017年10月6日
@author: yuthzi
'''
import datetime
t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:%M:%S")
t2 = datetime.datetime.strptime("2017-9-06 12:30:00", "%Y-%m-%d %H:%M:%S")
interval_time = (t2 - t1).seconds # 輸入的結果:7200
total_interval_time = (t2 - t1).total_seconds() # 輸出結果是: 7200.0
print interval_time
print total_interval_time
# 換一個方式
t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:%M:%S")
t2 = datetime.datetime.strptime("2017-9-08 12:30:00", "%Y-%m-%d %H:%M:%S")
interval_time = (t2 - t1).seconds # 輸入的結果:7200
total_interval_time = (t2 - t1).total_seconds() # 輸出結果是: 180000.0
print interval_time
print total_interval_time
td = (t2 - t1)
print((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)
# datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
td = datetime.timedelta(6, 5, 1, 800, 12, 3)
print td # 6 days, 3:12:05.800001
print td.seconds # 11525 忽略微秒和天
print td.total_seconds() # 529925.800001
import datetime
time_1 = '2021-09-17 08:45:56'
time_2 = '2021-09-17 08:30:00'
time_1_struct = datetime.datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")
time_2_struct = datetime.datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")
print((time_1_struct - time_2_struct).total_seconds()) # 輸出:956.0
print((time_1_struct - time_2_struct).seconds) # 輸出:956
interval_time = (time_2_struct - time_1_struct).seconds # 輸出的結果:85444
total_interval_time = (time_2_struct - time_1_struct).total_seconds() # 輸出結果是: -956.0
######日期不同
time_1 = '2021-09-16 08:45:56'
time_2 = '2021-09-17 08:30:00'
time_1_struct = datetime.datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")
time_2_struct = datetime.datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")
print((time_1_struct - time_2_struct).total_seconds()) # 輸出:-85444.0
print((time_1_struct - time_2_struct).seconds) # 輸出:956