赞
踩
1.获取当前时间的时间错
if __name__ == '__main__':
t = time.time()
print(t) # 原始时间数据 1575598311.9527097
print(int(t)) # 秒级时间戳 1575598311
print(int(round(t * 1000))) # 毫秒级时间戳 1575598311953
print(int(round(t * 1000000))) # 微秒级时间戳 1575598311952710
2.获取当前时间,包含格式
strftime:时间格式化,使用方式 time.strftime(format)
if __name__ == '__main__':
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #2019-12-06 10:13:52
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 含微秒的日期时间,来源 比特量化 2019-12-06 10:13:52.018611
3.将日期转为秒级时间戳
if __name__ == '__main__':
dt = '2019-12-06 10:13:52'
timearr = time.strptime(dt, "%Y-%m-%d %H:%M:%S");#转换为时间数组
print(timearr) #time.struct_time(tm_year=2019, tm_mon=12, tm_mday=6, tm_hour=10, tm_min=13, tm_sec=52, tm_wday=4, tm_yday=340, tm_isdst=-1)
ts = int(time.mktime(timearr))
print(ts) #1575598432
4.将时间戳转换为时间
if __name__ == '__main__':
ts = 1515774430
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
print(dt) #2018-01-13 00:27:10
5.时间格式转换
用到了datetime
if __name__ == '__main__':
dt = '12/02/2019 01:00:10'
dt_new = datetime.datetime.strptime(dt, '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
print(dt_new) #2019-12-02 01:00:10
未完待续
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。