标签:cond 时间转换 名称 转化 格式化 time 结构化 ptime oat
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
中文:
import time # 中文 import locale locale.setlocale(locale.LC_CTYPE, "chinese") s = time.strftime("%Y年%m月%d日") print(s) # 2018年11月18日
日期格式化标准:
时间戳不能直接转化成格式化时间,须先转化为结构化时间,再由结构化时间转化为格式化时间
同理,格式化时间转化为时间戳,须先转化为结构化时间,再由结构化时间转化为时间戳
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
将格式化时间转化为结构化时间
将结构化时间转化为时间戳
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
方法一:
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分钟
标签:cond 时间转换 名称 转化 格式化 time 结构化 ptime oat
原文地址:https://www.cnblogs.com/ipython-201806/p/9957922.html