2018-06-24

2018-09-08  本文已影响0人  baixuetang11

python时间转换

1、获取秒级时间戳与毫秒级时间戳

import timeimport datetime

t = time.time()

print(t)    #原始时间数据‘

print(int(t))#秒级时间戳

print(int(round(t * 1000)))#毫秒级时间戳

nowTime =lambda:int(round(t * 1000))

print(nowTime());#毫秒级时间戳,基于lambda

print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))#日期格式化

返回

1499825149.26

1499825149

1499825149257

1499825149257

2017-07-12 10:05:49

2、将字符串转为秒级时间戳

dt ='2018-01-01 10:40:30'

ts = int(time.mktime(time.strptime(dt,"%Y-%m-%d %H:%M:%S")))

print(ts)

返回

1514774430

3、将字符串转为日期结构

dt ='2018-01-01 10:40:30'

ts = time.strptime(dt,"%Y-%m-%d %H:%M:%S")

print(ts)

返回

time.struct_time(tm_year=2018, tm_mon=6, tm_mday=24, tm_hour=10, tm_min=20, tm_sec=30, tm_wday=6, tm_yday=175, tm_isdst=-1)

4、将秒级时间戳转为日期

ts = 1515774430

dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))

print(dt)

返回

2018-01-13 00:27:10

5、将当前秒级时间戳转为日期

dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

print(dt)

上一篇下一篇

猜你喜欢

热点阅读