1、time 獲取秒級時間戳,格式化顯示
import time
ts = time.time()
print("time:", ts) # 原始時間數(shù)據(jù),單位為秒
# time.strptime 只支持到秒級別!
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) # 轉(zhuǎn) UTC時間,精確到秒print("time UTC str:", dt)
print("time UTC ms str:", dt + f".%.3f" % ((ts - int(ts)) * 1000)) # 顯示毫秒和微秒
結(jié)果:
time: 1685594545.0012841
time m str: 2023-06-01 12:42:25
time ms str: 2023-06-01 12:42:25.1.284
2、datetime 獲取當(dāng)前日期時間
# 獲取含微秒的日期時間 print(dt_ms)
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
print(dt_ms)
結(jié)果:
2023-06-01 12:45:13.345816
3、日期時間之間的轉(zhuǎn)換
3.1、字符串轉(zhuǎn) time
dt = '2018-01-01 10:40:30'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
print (ts)
=>
1514774430
3.2、字符串轉(zhuǎn) time文章來源:http://www.zghlxwxcb.cn/news/detail-598967.html
ts = 1515774430
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
print(dt)
=>
2018-01-13 00:27:10
3.3、示例文章來源地址http://www.zghlxwxcb.cn/news/detail-598967.html
ts = time.mktime(time.strptime("2023-06-05", "%Y-%m-%d")) # 1685894400.0
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1685894400.0)) # 2023-06-05 00:00:00'
到了這里,關(guān)于python time 獲取毫秒級時間戳的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!