python常用時間庫time、datetime與時間格式之間的轉換教程
本文將對python中多個時間儲存方式、時間模塊(如time、datetime、timeit)以及他們之間的轉換關系進行詳細的梳理和總結。整體梳理后表示圖如下:

一,python中儲存時間的三種格式
1,時間元組(結構體時間)
共有九個元素組

2,時間戳
時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量
3,格式化時間
已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。
二、time庫
1,time.time()
創(chuàng)建時間戳
返回當前時間的時間戳(1970紀元后經(jīng)過的浮點秒數(shù))。
import time # 返回當前時間的時間戳(1970紀元后經(jīng)過的浮點秒數(shù))。 temp = time.time() print(temp,type(temp)) # -----out------ # 1567667448.120967 <class 'float'>
2,time.localtime([ sec ])
創(chuàng)建結構體時間 | 將時間戳轉換為結構體時間(本地)
格式化時間戳為本地的時間,返回結構體時間。若sec參數(shù)未輸入,則以當前時間為轉換。
import time # 1,localtime中加入時間戳參數(shù) temp = time.time() # localtime輸入時間戳參數(shù),將時間戳轉化為本地時間 locaoltime = time.localtime(temp) print(locaoltime,type(locaoltime)) time.sleep(3) # 2,localtime未輸入?yún)?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 ])
將時間戳轉換為結構體時間(0時區(qū))
將一個時間戳轉換為UTC時區(qū)(0時區(qū))的struct_time,可選的參數(shù)sec表示從1970-1-1以來的秒數(shù)。其默認值為time.time(),函數(shù)返回time.struct_time類型的對象。(struct_time是在time模塊中定義的表示時間的對象)。
import time temp = time.time() # localtime輸入時間戳參數(shù),將時間戳轉化為本地時間 print(time.localtime(temp),type(time.localtime(temp))) # gmtimee輸入時間戳參數(shù),將時間戳轉換為UTC時區(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])
將結構體時間轉換為字符串
輸入結構體時間,輸出為按照輸入的格式的字符串
import time
# 輸入結構體時間,輸出為按照輸入的格式的字符串
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])
將字符串轉換為結構體時間
根據(jù)指定的格式把一個時間字符串解析為結構體時間。
import time
# 輸入結構體時間,輸出為按照輸入的格式的字符串
temps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(temps,type(temps))
strs = temps
# 輸入字符串,按照參數(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)
將結構體時間轉換為時間戳 接收struct_time對象作為參數(shù),返回用秒數(shù)來表示時間的浮點數(shù)。
如果輸入的值不是一個合法的時間,將觸發(fā) OverflowError 或 ValueError。
import time # 輸入結構體時間,返回時間戳 time_temps = time.mktime(time.localtime()) print(time_temps,type(time_temps)) # -----out------ # 1567672723.0 <class 'float'>
7,time.sleep(nums)
推遲執(zhí)行的秒數(shù),沒有任何輸出
import time # 推遲執(zhí)行的秒數(shù),沒有任何輸出 temp = time.sleep(3) print(temp,type(temp)) # -----out------ # None <class 'NoneType'>
8,timeit.Timer.timeit([number])
用來計算一個函數(shù)平均執(zhí)行了多少時間
# coding=gbk
import timeit
def T1():
'''表內置屬性'''
li = []
for i in range(1000):
li.append(i)
def T2():
'''列表拼接'''
li = []
for i in range(1000):
li = li + [i]
def T3():
'''列表推導式'''
li = [i for i in range(1000)]
def T4():
'''屬性轉換'''
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庫
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,以默認的格式返回日期
print(someday.isoformat())
# 4,獲得今天日期,返回datetime類型
temp = datetime.date.today()
print(temp,type(temp))
# 5,根據(jù)給定的時間戮,返回一個date對象
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ù)包括hour、minute、second、microsecond。 time類的方法同datetime類。
import datetime
import time
# 1,以下為兩種生成時間的方式,效果一致,返回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ī)定的格式返回時間,返回字符串類型
temp = someday.strftime('%H::%M::%S')
print(temp,type(temp))
#
# 3,以默認的格式返回時間
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ù)包含year、month、day、hour、minute、second、microsecond。但是至少要包含year、month、day三個參數(shù)。
import datetime
import time
# 1,以下為兩種生成日期時間的方式,效果一致,返回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ī)定的格式返回日期時間,返回字符串類型
temp = someday.strftime('%Y-%m-%d %H:%M:%S')
print(temp,type(temp))
# 3,以默認的格式返回日期時間
print(someday.isoformat(),type(someday))
# 4,datetime類.timetuple()將datetime轉化為結構體時間;再通過time.mktime()裝換為時間戳
dtime = datetime.datetime.now()
print(dtime.timetuple(),type(dtime.timetuple()))
un_time = time.mktime(dtime.timetuple())
print(un_time,type(un_time))
# 5,時間戳轉換為python的datetime
times = datetime.datetime.fromtimestamp(un_time)
print(times,type(times))
# 6,將datetime類轉換為格式化時間,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,將格式化時間轉換為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ù)包含days、hours、minutes、seconds、microseconds。
import datetime # 以下為1天零1小時零1分零1秒又10毫秒的時間間隔 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,當前時間和日期 print(datetime.datetime.now()) # 2,根據(jù)指定日期、相隔時間計算出對應目標時間 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模塊之間的相互轉換
# coding=utf-8
import time
import datetime
def get_time():
# 獲取當前datetime類型時間
now_time = datetime.datetime.now()
# 當前時間減去一天 獲得昨天當前時間
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類型計算兩個時間之間差值
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 注意這樣計算出的秒數(shù)只有小時之后的計算額 也就是不包含天之間差數(shù)
def unix_time():
#將python的datetime轉換為unix時間戳
dtime = datetime.datetime.now()
un_time = time.mktime(dtime.timetuple())
print (un_time)
#將unix時間戳轉換為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()
五,附錄

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

