1、time 获取秒级时间戳,格式化显示
import time
ts = time.time()
print("time:", ts) # 原始时间数据,单位为秒
# time.strptime 只支持到秒级别!
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) # 转 UTC时间,精确到秒print("time UTC str:", dt)
print("time UTC ms str:", dt + f".%.3f" % ((ts - int(ts)) * 1000)) # 显示毫秒和微秒
结果:
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 获取当前日期时间
# 获取含微秒的日期时间 print(dt_ms)
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
print(dt_ms)
结果:
2023-06-01 12:45:13.345816
3、日期时间之间的转换
3.1、字符串转 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、字符串转 time文章来源:https://www.toymoban.com/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、示例文章来源地址https://www.toymoban.com/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'
到了这里,关于python time 获取毫秒级时间戳的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!