import time print(time.time()) # 1542203668.0212119
import time s = time.strftime("%Y-%m-%d %H:%M:%S") print(s) # 2018-11-14 22:01:40
中文:spa
import time # 中文 import locale locale.setlocale(locale.LC_CTYPE, "chinese") s = time.strftime("%Y年%m月%d日") print(s) # 2018年11月18日
日期格式化標準:code
時間戳不能直接轉化成格式化時間,須先轉化爲結構化時間,再由結構化時間轉化爲格式化時間blog
同理,格式化時間轉化爲時間戳,須先轉化爲結構化時間,再由結構化時間轉化爲時間戳string
import time t = time.localtime(1888888888) print(t) # time.struct_time(tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=11, tm_min=21, tm_sec=28, tm_wday=4, tm_yday=313, tm_isdst=0) s = time.strftime("%Y-%m-%d %H:%M:%S", t) print(s) # 2029-11-09 11:21:28
import time t = time.gmtime(1888888888) print(t) # time.struct_time(tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=3, tm_min=21, tm_sec=28, tm_wday=4, tm_yday=313, tm_isdst=0) s = time.strftime("%Y-%m-%d %H:%M:%S", t) print(s) # 2029-11-09 03:21:28
import time t = time.localtime(1888888888) print(t) # time.struct_time(tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=11, tm_min=21, tm_sec=28, tm_wday=4, tm_yday=313, tm_isdst=0) s = time.strftime("%Y-%m-%d %H:%M:%S", t) print(s) # 2029-11-09 11:21:28
將格式化時間轉化爲結構化時間class
將結構化時間轉化爲時間戳import
import time s = "2029-11-09 11:21:28" t = time.strptime(s, "%Y-%m-%d %H:%M:%S") print(t) # time.struct_time(tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=11, tm_min=21, tm_sec=28, tm_wday=4, tm_yday=313, tm_isdst=-1) tt = time.mktime(t) print(tt) # 1888888888.0
方法一:float
import time begin = "2018-11-14 16:30:00" end = "2018-11-14 18:00:00" begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S") end_struct_time = time.strptime(end, "%Y-%m-%d %H:%M:%S") begin_second = time.mktime(begin_struct_time) end_second = time.mktime(end_struct_time) diff_time_sec = end_second - begin_second diff_hour, diff_min_1 = divmod(diff_time_sec, 3600) diff_min, diff_sec = divmod(diff_min_1, 60) print("時間差是 %s小%s分鐘%s秒" % (int(diff_hour), int(diff_min), int(diff_sec))) 結果: 時間差是 1小30分鐘0秒
方法二:方法
import time begin = "2018-11-14 16:30:00" end = "2018-11-14 18:00:00" begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S") end_struct_time = time.strptime(end, "%Y-%m-%d %H:%M:%S") begin_second = time.mktime(begin_struct_time) end_second = time.mktime(end_struct_time) diff_time_sec = abs(begin_second - end_second) # 秒級時間差 # 轉化成結構化時間 t = time.gmtime(diff_time_sec) # 用格林尼治時間,不然會有時間差 # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=1, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) print("時間差是%s年 %s月 %s天 %s小時 %s分鐘" % (t.tm_year - 1970, t.tm_mon - 1, t.tm_mday - 1, t.tm_hour, t.tm_min)) 結果: 時間差是0年 0月 0天 1小時 30分鐘