時間模塊
time模塊
獲取秒級時間戳、毫秒級時間戳、微秒級時間戳
import time t = time.time() print t # 原始時間數據 1574502460.90 print int(t) # 秒級時間戳:10位 1574502460 print int(round(t * 1000)) # 毫秒級時間戳:13位 1574502460904 print int(round(t * 1000000)) # 微秒級時間戳:16位 1574502460903997
格式化日期與秒級時間戳之間的轉換
import time # 將日期轉為秒級時間戳 dt = '2019-08-08 10:00:00' ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S"))) print ts # 結果:1565229600 # 將秒級時間戳轉為日期 ts = 1565229600 dt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts)) print dt # 結果:2019-08-08 10:00:00 # 將當前秒級時間戳轉為日期,下面兩種寫法的結果是一樣的 ct = time.strftime('%Y-%m-%d %H:%M:%S') ct = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print ct, type(ct) # 結果:2019-11-25 09:45:09 <type 'str'>
轉結構體時間struct_time
# 日期時間轉結構體 ta_dt = time.strptime("2019-11-25 10:20:50", '%Y-%m-%d %H:%M:%S') print ta_dt # time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=10, tm_min=20, tm_sec=50, tm_wday=0, tm_yday=329, tm_isdst=-1) # 時間戳轉結構體,注意時間戳要求為int,也可以不帶參數:ta_ms = time.localtime() ta_ms = time.localtime(1574648450) print ta_ms # time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=10, tm_min=20, tm_sec=50, tm_wday=0, tm_yday=329, tm_isdst=0) print ta_ms[0], ta_ms[1], ta_ms[2], ta_ms[3], ta_ms[4], ta_ms[5]
其他用法
print time.time() # 結果:1574655005.15,現在距離計算機元年過去了多少秒。 print time.ctime() # 結果:Mon Nov 25 12:10:05 2019 print time.sleep(3) # 結果:程序運行到這兒,暫停3秒,休眠3秒。 print time.asctime((2019,5,7,20,8,8,6,3,1)) # 結果:Sun May 7 20:08:08 2019 print time.mktime((2019,5,9,20,8,8,0,0,0)) # 結果:1557403688.0 print time.gmtime(7200) # 結果:time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) print time.gmtime(1557403688) # 結果:time.struct_time(tm_year=2019, tm_mon=5, tm_mday=9, tm_hour=12, tm_min=8, tm_sec=8, tm_wday=3, tm_yday=129, tm_isdst=0) print time.localtime(1557403688.0) # 結果:time.struct_time(tm_year=2019, tm_mon=5, tm_mday=9, tm_hour=20, tm_min=8, tm_sec=8, tm_wday=3, tm_yday=129, tm_isdst=0) print time.localtime() # 結果:time.struct_time(tm_year=2019, tm_mon=11, tm_mday=25, tm_hour=12, tm_min=10, tm_sec=8, tm_wday=0, tm_yday=329, tm_isdst=0)
datetime模塊
dateutil模塊
from dateutil.parser import parse t1 = parse('2019-10-01 10:10:10') t2 = parse('2019-10-01/10:10:10') t3 = parse('2019/12/01 10:10:10') t4 = parse('2019/12/01/10:10:10') print t1, type(t1) # 2019-10-01 10:10:10 <type 'datetime.datetime'> print t2, type(t2) # 2019-10-01 10:10:10 <type 'datetime.datetime'> print t3, type(t3) # 2019-12-01 10:10:10 <type 'datetime.datetime'> print (t3-t1).days # 61 print (t3-t1).seconds # 0 print (t3-t1).total_seconds() # 5270400.0
https://www.cnblogs.com/mashuqi/p/11576705.html
https://www.jianshu.com/p/f29dddce3a9a
隨機模塊