python存在兩個時間類time/dateTime
區別:
time:在python文檔中,time是歸類在常規操作系統服務中,它提供的功能更加接近於操作系統層面。其所能表述的日期范圍被限定在1970-2038之間,如果需要表述范圍之外的日期,可能需要考慮使用datetime模塊更好。
datetime:比time高級了不少,可以理解為datetime基於time進行了封裝,提供了更多實用的函
用法:
簡介時間元組(struct_time):
tm_year:年1-12
tm_mon:月1-12
tm_mday:日1-31
tm_hour:時0-23
tm_min:分0-59
tm_sec:秒0-59
tm_wday:星期0-6(0表示周日)
tm_day:一年中的第幾天1-366
tm_isdst:是否是夏令,默認為-1
time:
time.sleep(sec):推遲指定時間sec后繼續運行
time.localtime([sec]):將一個時間戳轉化成一個當時時區的struct_time,如果sec參數未輸入,則以當前時間為轉化標准
time.strftime(format[,t]):將指定的struct_time(默認為當前時間),根據指定的格式化字符串輸出
time.time():返回當前時間的時間戳(以秒表示的浮點數)
time.mktime(t):將一個struct_time轉換為時間戳
time.gmtime([sec]):將一個時間戳轉化為UTC時區(0時區)的struct_time
time.clock():不同系統含義不同。UNIX——返回進程時間,WINS第一次調用返回進程運行的實際時間,第二次調用是自第一次調用以后到現在的運行時間
time.asctime([t])把一個時間的元組或者struct_time表示為“Sun Jun 20 23:21:05 1993”,如果無參數,則會把time.localtime()作為參數傳入
time.ctime([sec]):把一個時間戳轉化為time.asctime()的形式,如果無參數或者為None時,則會把time.time()作為參數傳入。它的作用相當於time.asctime(time.localtime(sec))
time.strftime(format[,t]):把一個代表時間的元組或者struct_time轉化為格式化的時間字符串。如果t為指定,將傳入time.localtime()。如果元組中任何一個元素越界,ValueError的錯誤將會被拋出
datetime:
提供類方法如下:
timedelta:主要用於計算時間跨度
tzinfo:時區相關
time:只關注時間
date:只關注日期
datetime:同時有時間和日期
實際使用中用的比較多的是:datetime.datetime 和 datetime.timedelta
datetime.year
datetime.month
datetime.day
datetime.hour
datetime.minute
datetime.second
datetime.microsecond
datetime.tzinfo():時區
datetime.date():返回date對象
datetime.time():返回time對象
datetime.replace(name=value)
datetime.timetuple():返回time.struct_time 對象
datetime.strftime(format):按照format進行格式化輸出
計算時間精確到時分秒:
from datetime import datetime oldtime= datetime(2020,10,26, 11,00,38) newtime= datetime(2020,10,26, 18,00,38) print ((newtime-oldtime).seconds) #秒 print (round((newtime-oldtime).seconds/60)) #分 print (round((newtime-oldtime).seconds/3600)) #時 print ((newtime-oldtime).days) #日