python常用時(shí)間庫(kù)time、datetime與時(shí)間格式之間的轉(zhuǎn)換教程
本文將對(duì)python中多個(gè)時(shí)間儲(chǔ)存方式、時(shí)間模塊(如time、datetime、timeit)以及他們之間的轉(zhuǎn)換關(guān)系進(jìn)行詳細(xì)的梳理和總結(jié)。整體梳理后表示圖如下:

一,python中儲(chǔ)存時(shí)間的三種格式
1,時(shí)間元組(結(jié)構(gòu)體時(shí)間)
共有九個(gè)元素組

2,時(shí)間戳
時(shí)間戳表示的是從1970年1月1日00:00:00開(kāi)始按秒計(jì)算的偏移量
3,格式化時(shí)間
已格式化的結(jié)構(gòu)使時(shí)間更具可讀性。包括自定義格式和固定格式。
二、time庫(kù)
1,time.time()
創(chuàng)建時(shí)間戳
返回當(dāng)前時(shí)間的時(shí)間戳(1970紀(jì)元后經(jīng)過(guò)的浮點(diǎn)秒數(shù))。
import time # 返回當(dāng)前時(shí)間的時(shí)間戳(1970紀(jì)元后經(jīng)過(guò)的浮點(diǎn)秒數(shù))。 temp = time.time() print(temp,type(temp)) # -----out------ # 1567667448.120967 <class 'float'>
2,time.localtime([ sec ])
創(chuàng)建結(jié)構(gòu)體時(shí)間 | 將時(shí)間戳轉(zhuǎn)換為結(jié)構(gòu)體時(shí)間(本地)
格式化時(shí)間戳為本地的時(shí)間,返回結(jié)構(gòu)體時(shí)間。若sec參數(shù)未輸入,則以當(dāng)前時(shí)間為轉(zhuǎn)換。
import time # 1,localtime中加入時(shí)間戳參數(shù) temp = time.time() # localtime輸入時(shí)間戳參數(shù),將時(shí)間戳轉(zhuǎn)化為本地時(shí)間 locaoltime = time.localtime(temp) print(locaoltime,type(locaoltime)) time.sleep(3) # 2,localtime未輸入?yún)?shù)時(shí),默認(rèn)為當(dāng)時(shí)時(shí)間 print(time.localtime(),type(time.localtime())) # -----out------ # time.struct_time(tm_year=2019, tm_mon=9, tm_mday=5, tm_hour=15, tm_min=44, tm_sec=4, tm_wday=3, tm_yday=248, tm_isdst=0) <class 'time.struct_time'> # time.struct_time(tm_year=2019, tm_mon=9, tm_mday=5, tm_hour=15, tm_min=44, tm_sec=7, tm_wday=3, tm_yday=248, tm_isdst=0) <class 'time.struct_time'>
3,time gmtime([ sec ])
將時(shí)間戳轉(zhuǎn)換為結(jié)構(gòu)體時(shí)間(0時(shí)區(qū))
將一個(gè)時(shí)間戳轉(zhuǎn)換為UTC時(shí)區(qū)(0時(shí)區(qū))的struct_time,可選的參數(shù)sec表示從1970-1-1以來(lái)的秒數(shù)。其默認(rèn)值為time.time(),函數(shù)返回time.struct_time類型的對(duì)象。(struct_time是在time模塊中定義的表示時(shí)間的對(duì)象)。
import time temp = time.time() # localtime輸入時(shí)間戳參數(shù),將時(shí)間戳轉(zhuǎn)化為本地時(shí)間 print(time.localtime(temp),type(time.localtime(temp))) # gmtimee輸入時(shí)間戳參數(shù),將時(shí)間戳轉(zhuǎn)換為UTC時(shí)區(qū) print(time.gmtime(temp),type(time.gmtime(temp))) # -----out------ # time.struct_time(tm_year=2019, tm_mon=9, tm_mday=5, tm_hour=17, tm_min=8, tm_sec=57, tm_wday=3, tm_yday=248, tm_isdst=0) <class 'time.struct_time'> # time.struct_time(tm_year=2019, tm_mon=9, tm_mday=5, tm_hour=9, tm_min=8, tm_sec=57, tm_wday=3, tm_yday=248, tm_isdst=0) <class 'time.struct_time'>
4,time.strftime(format[, t])
將結(jié)構(gòu)體時(shí)間轉(zhuǎn)換為字符串
輸入結(jié)構(gòu)體時(shí)間,輸出為按照輸入的格式的字符串
import time
# 輸入結(jié)構(gòu)體時(shí)間,輸出為按照輸入的格式的字符串
temps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(temps,type(temps))
# -----out------
# 2019-09-05 17:12:34 <class 'str'>
5,time.strptime(string[, format])
將字符串轉(zhuǎn)換為結(jié)構(gòu)體時(shí)間
根據(jù)指定的格式把一個(gè)時(shí)間字符串解析為結(jié)構(gòu)體時(shí)間。
import time
# 輸入結(jié)構(gòu)體時(shí)間,輸出為按照輸入的格式的字符串
temps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(temps,type(temps))
strs = temps
# 輸入字符串,按照參數(shù)指定格式,輸出結(jié)構(gòu)體時(shí)間
temps = time.strptime( strs,"%Y-%m-%d %H:%M:%S")
print(temps,type(temps))
# -----out------
# 2019-09-05 16:20:58 <class 'str'>
# time.struct_time(tm_year=2019, tm_mon=9, tm_mday=5, tm_hour=16, tm_min=20, tm_sec=58, tm_wday=3, tm_yday=248, tm_isdst=-1) <class 'time.struct_time'>
6,time mktime(t)
將結(jié)構(gòu)體時(shí)間轉(zhuǎn)換為時(shí)間戳 接收struct_time對(duì)象作為參數(shù),返回用秒數(shù)來(lái)表示時(shí)間的浮點(diǎn)數(shù)。
如果輸入的值不是一個(gè)合法的時(shí)間,將觸發(fā) OverflowError 或 ValueError。
import time # 輸入結(jié)構(gòu)體時(shí)間,返回時(shí)間戳 time_temps = time.mktime(time.localtime()) print(time_temps,type(time_temps)) # -----out------ # 1567672723.0 <class 'float'>
7,time.sleep(nums)
推遲執(zhí)行的秒數(shù),沒(méi)有任何輸出
import time # 推遲執(zhí)行的秒數(shù),沒(méi)有任何輸出 temp = time.sleep(3) print(temp,type(temp)) # -----out------ # None <class 'NoneType'>
8,timeit.Timer.timeit([number])
用來(lái)計(jì)算一個(gè)函數(shù)平均執(zhí)行了多少時(shí)間
# coding=gbk
import timeit
def T1():
'''表內(nèi)置屬性'''
li = []
for i in range(1000):
li.append(i)
def T2():
'''列表拼接'''
li = []
for i in range(1000):
li = li + [i]
def T3():
'''列表推導(dǎo)式'''
li = [i for i in range(1000)]
def T4():
'''屬性轉(zhuǎn)換'''
li = list(range(1000))
if __name__ == "__main__":
test_list = ['T1()','T2()','T3()','T4()']
for i in test_list:
timer = timeit.Timer(i,"from __main__ import T1,T2,T3,T4")
print("%s: %f seconds" % (i,timer.timeit(number=1000)))
三,datetime庫(kù)
datetime模塊包含如下類

1,datetime.date類
表示日期的類,常用的屬性有year、month、day。參數(shù)都為整數(shù)。
import datetime
import time
# 1,以下為兩種生成日期的方式,效果一致,返回datetime類型
someday = datetime.date(year=2018, month=1, day=1)
someday = datetime.date(2018, 1, 1)
print(someday,type(someday))
# 2,以規(guī)定的格式返回日期,返回字符串類型
temp = someday.strftime('/%Y/%m/%d')
print(temp,type(someday))
# 3,以默認(rèn)的格式返回日期
print(someday.isoformat())
# 4,獲得今天日期,返回datetime類型
temp = datetime.date.today()
print(temp,type(temp))
# 5,根據(jù)給定的時(shí)間戮,返回一個(gè)date對(duì)象
temp = datetime.date.fromtimestamp(time.time())
print(temp)
# -----out------
# 2018-01-01 <class 'datetime.date'>
# /2018/01/01 <class 'datetime.date'>
# 2018-01-01
# 2019-09-05 <class 'datetime.date'>
# 2019-09-05
2,datetime.time類
表示時(shí)間的類,參數(shù)包括hour、minute、second、microsecond。 time類的方法同datetime類。
import datetime
import time
# 1,以下為兩種生成時(shí)間的方式,效果一致,返回datetime類型
someday = datetime.time(hour=12,minute=50,second=12,microsecond=10)
someday = datetime.time(12, 50, 12, 10)
print(someday,type(someday))
# 2,以規(guī)定的格式返回時(shí)間,返回字符串類型
temp = someday.strftime('%H::%M::%S')
print(temp,type(temp))
#
# 3,以默認(rèn)的格式返回時(shí)間
print(someday.isoformat(),type(someday))
# -----out------
# 12:50:12.000010 <class 'datetime.time'>
# 12::50::12 <class 'str'>
# 12:50:12.000010 <class 'datetime.time'>
3,datetime.datetime類
日期實(shí)踐類,常用的參數(shù)包含year、month、day、hour、minute、second、microsecond。但是至少要包含year、month、day三個(gè)參數(shù)。
import datetime
import time
# 1,以下為兩種生成日期時(shí)間的方式,效果一致,返回datetime類型
someday = datetime.datetime(year=2018,month=1,day=1,hour=12,minute=50,second=12,microsecond=10)
someday = datetime.datetime(2018, 1, 1, 12, 50, 12, 10)
print(someday,type(someday))
# 2,以規(guī)定的格式返回日期時(shí)間,返回字符串類型
temp = someday.strftime('%Y-%m-%d %H:%M:%S')
print(temp,type(temp))
# 3,以默認(rèn)的格式返回日期時(shí)間
print(someday.isoformat(),type(someday))
# 4,datetime類.timetuple()將datetime轉(zhuǎn)化為結(jié)構(gòu)體時(shí)間;再通過(guò)time.mktime()裝換為時(shí)間戳
dtime = datetime.datetime.now()
print(dtime.timetuple(),type(dtime.timetuple()))
un_time = time.mktime(dtime.timetuple())
print(un_time,type(un_time))
# 5,時(shí)間戳轉(zhuǎn)換為python的datetime
times = datetime.datetime.fromtimestamp(un_time)
print(times,type(times))
# 6,將datetime類轉(zhuǎn)換為格式化時(shí)間,datetime類.strftime(format).
now_time = datetime.datetime.now()
now_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
print(now_time,type(now_time))
# 7,將格式化時(shí)間轉(zhuǎn)換為datetime類,datetime.datetime.strptime(string,format)
d2 = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
print(d2,type(d2))
# -----out------
# 2018-01-01 12:50:12.000010 <class 'datetime.datetime'>
# 2018-01-01 12:50:12 <class 'str'>
# 2018-01-01T12:50:12.000010 <class 'datetime.datetime'>
# time.struct_time(tm_year=2019, tm_mon=9, tm_mday=6, tm_hour=11, tm_min=13, tm_sec=59, tm_wday=4, tm_yday=249, tm_isdst=-1) <class 'time.struct_time'>
# 1567739639.0 <class 'float'>
# 2019-09-06 11:13:59 <class 'datetime.datetime'>
# 2019-09-06 11:13:59 <class 'str'>
# 2019-09-06 11:13:59 <class 'datetime.datetime'>
4,datetime.timedelta類
表示時(shí)間間隔類,給一個(gè)時(shí)間點(diǎn)加上此類,即可得到一個(gè)新的時(shí)間。參數(shù)包含days、hours、minutes、seconds、microseconds。
import datetime # 以下為1天零1小時(shí)零1分零1秒又10毫秒的時(shí)間間隔 datetime.timedelta(days=1,hours=1,minutes=1,seconds=1,microseconds=10) datetime.timedelta(1, 3661, 10) # 以下為35天間隔 datetime.timedelta(days=35) datetime.timedelta(35) # 1,當(dāng)前時(shí)間和日期 print(datetime.datetime.now()) # 2,根據(jù)指定日期、相隔時(shí)間計(jì)算出對(duì)應(yīng)目標(biāo)時(shí)間 temp= datetime.datetime.now()-datetime.timedelta(days=67) print(temp) print(datetime.datetime.now()-datetime.timedelta(hours=10,days=1)) # -----out------ # 2019-09-05 20:05:30.396688 # 2019-06-30 20:05:30.396688 # 2019-09-04 10:05:30.396688
四,time模塊和datetime模塊之間的相互轉(zhuǎn)換
# coding=utf-8
import time
import datetime
def get_time():
# 獲取當(dāng)前datetime類型時(shí)間
now_time = datetime.datetime.now()
# 當(dāng)前時(shí)間減去一天 獲得昨天當(dāng)前時(shí)間
yes_time = now_time + datetime.timedelta(days=-1)
# 格式化輸出
yes_time_str = yes_time.strftime('%Y-%m-%d %H:%M:%S')
print (yes_time_str) # 2017-11-01 22:56:02
def dif_time():
# 使用datetime類型計(jì)算兩個(gè)時(shí)間之間差值
now_time = datetime.datetime.now()
now_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
d1 = datetime.datetime.strptime('2017-10-16 19:21:22', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
#間隔天數(shù)
day = (d2 - d1).days
#間隔秒數(shù)
second = (d2 - d1).seconds
print (day) #17
print (second) #13475 注意這樣計(jì)算出的秒數(shù)只有小時(shí)之后的計(jì)算額 也就是不包含天之間差數(shù)
def unix_time():
#將python的datetime轉(zhuǎn)換為unix時(shí)間戳
dtime = datetime.datetime.now()
un_time = time.mktime(dtime.timetuple())
print (un_time)
#將unix時(shí)間戳轉(zhuǎn)換為python的datetime
unix_ts = 1509636585.0
times = datetime.datetime.fromtimestamp(unix_ts)
print (times) #2017-11-02 23:29:45
if __name__ == "__main__":
get_time()
dif_time()
五,附錄

總結(jié)
到此這篇關(guān)于python常用時(shí)間庫(kù)time、datetime與時(shí)間格式之間轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)python時(shí)間庫(kù)time、datetime與時(shí)間格式轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 中數(shù)組和數(shù)字相乘時(shí)的注意事項(xiàng)說(shuō)明
這篇文章主要介紹了Python 中數(shù)組和數(shù)字相乘時(shí)的注意事項(xiàng)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05
python 時(shí)間信息“2018-02-04 18:23:35“ 解析成字典形式的結(jié)果代碼詳解
本文是類方法給大家介紹如何將python 時(shí)間信息“2018-02-04 18:23:35“ 解析成字典形式的結(jié)果,需要的朋友可以參考下2018-04-04
詳解Python如何實(shí)現(xiàn)查看WiFi密碼
這篇文章主要為大家詳細(xì)介紹了如何使用python來(lái)試試看看能不能讀取到已連接過(guò)WIFI的密碼,文中的示例代碼講解詳細(xì),?感興趣的小伙伴可以了解下2023-11-11
使用 Python 實(shí)現(xiàn)簡(jiǎn)單的 switch/case 語(yǔ)句的方法
這篇文章主要介紹了用 Python 實(shí)現(xiàn)簡(jiǎn)單的 switch/case 語(yǔ)句的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09
TensorFlow神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)之張量與變量概念
這篇文章主要為大家介紹了TensorFlow神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)的基本知識(shí)張量與變量概念詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10

