資訊內(nèi)容
python怎么計(jì)算時(shí)間差
python計(jì)算時(shí)間差的方法:首先引入datetime包;然后通過“(time_2_struct - time_1_struct)”方式計(jì)算出同一天情形下的時(shí)間差或者不同天的時(shí)間差即可。43m少兒編程網(wǎng)-https://www.pxcodes.com
43m少兒編程網(wǎng)-https://www.pxcodes.com
本文操作環(huán)境:windows7系統(tǒng)、python2.7.14版,DELL G3電腦。43m少兒編程網(wǎng)-https://www.pxcodes.com
python求時(shí)間差43m少兒編程網(wǎng)-https://www.pxcodes.com
python求時(shí)間差主要是用的datetime包,包括同一天情形下的時(shí)間差和不同天情形下的時(shí)間差。43m少兒編程網(wǎng)-https://www.pxcodes.com
from datetime import datetime, date1. 同一天情形下的時(shí)間差(秒)seconds ,分鐘由秒數(shù)除以60即可43m少兒編程網(wǎng)-https://www.pxcodes.com
#計(jì)算時(shí)間差的分鐘數(shù) # 同一天的時(shí)間差 time_1 = '2020-03-02 15:00:00' time_2 = '2020-03-02 16:00:00' time_1_struct = datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S") time_2_struct = datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S") seconds = (time_2_struct - time_1_struct).seconds print('同一天的秒數(shù)為:') print(seconds)43m少兒編程網(wǎng)-https://www.pxcodes.com
2. 不同天情形下的時(shí)間差(也可計(jì)算同一天情形下的時(shí)間差),total_seconds43m少兒編程網(wǎng)-https://www.pxcodes.com
# 不同天的時(shí)間差 time_1 = '2020-03-02 15:00:00' time_2 = '2020-03-03 16:00:00' time_1_struct = datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S") time_2_struct = datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S") # 來獲取時(shí)間差中的秒數(shù)。注意,seconds獲得的秒只是時(shí)間差中的小時(shí)、分鐘和秒部分,沒有包含天數(shù)差,total_seconds包含天數(shù)差 # 所以total_seconds兩種情況都是可以用的 total_seconds = (time_2_struct - time_1_struct).total_seconds() print('不同天的秒數(shù)為:') print(int(total_seconds)) min_sub = total_seconds / 60 print('不同天的分鐘數(shù)為:') print(int(min_sub))43m少兒編程網(wǎng)-https://www.pxcodes.com
【推薦學(xué)習(xí):python視頻教程】43m少兒編程網(wǎng)-https://www.pxcodes.com
3. 只有時(shí)間time沒有日期時(shí),求時(shí)間差先可以加上一個(gè)相同的日期,再求時(shí)間差,datetime.combine 方法43m少兒編程網(wǎng)-https://www.pxcodes.com
# 只有時(shí)間time沒有日期時(shí),求時(shí)間差先可以加上一個(gè)相同的日期,再求時(shí)間差 # date.min能表示的**小日期 # date.max能表示的**大日期 # date.today()返回一個(gè)當(dāng)前日期對(duì)象 # datetime.combine:根據(jù)所給的date和time創(chuàng)建一個(gè)datetime對(duì)象 time_sub = datetime.combine(date.min, time_2_struct.time()) - datetime.combine(date.min, time_1_struct.time()) print('----- 與**小日期結(jié)合: ------') print(time_sub.seconds/60) time_sub = datetime.combine(date.today(), time_2_struct.time()) - datetime.combine(date.today(), time_1_struct.time()) print('----- 與當(dāng)天日期結(jié)合: ------') print(time_sub.seconds/60) print(time_sub.total_seconds()/60)以上就是python怎么計(jì)算時(shí)間差的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注少兒編程網(wǎng)其它相關(guān)文章!43m少兒編程網(wǎng)-https://www.pxcodes.com

- 上一篇
python如何終止線程前言 · 零解決方案 · 壹解決方案 · 貳解決方案 · 叁
簡(jiǎn)介python終止線程的方法:1、調(diào)用stop函數(shù),并使用join函數(shù)來等待線程合適地退出;2、在python線程里面raise一個(gè)Exception;3、用“thread.join”方式結(jié)束線程。本文操作環(huán)境:windows7系統(tǒng)、python3.5版,DELLG3電腦。前言·零我們知道,在pyth
- 下一篇
python中+=是什么意思
簡(jiǎn)介python中+=的意思:1、兩個(gè)值相加,返回值給符號(hào)左側(cè)的變量;2、用于字符串連接,變量值帶引號(hào),數(shù)據(jù)類型為字符串。本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,DELLG3電腦,該方法適用于所有品牌電腦。python中+=的意思:1、+=其實(shí)很容易理解2、例如:C+=0.1就等于C