赞
踩
>>> import time
>>> timestamp = time.time()
>>> timestamp
1688548167.190377
以毫秒计时的时间戳一般有 13 位,可以将其除以 1000:
timestamp13 = 1688548167190
timestamp = timestamp13 / 1000
使用 datetime 库,将时间戳转换为时间:
# 1688548167.190377 -> "2023-07-05 17:09:27.190377"
import datetime as dt
def timestamp_to_timestr(timestamp):
# return dt.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S.%f")
return dt.datetime.fromtimestamp(timestamp)
print(timestamp_to_timestr(timestamp))
2023-07-05 17:09:27.190377
也可以只用 time 库进行转换:
# 1688548167190 -> 2023-07-05 17:09:27
def timestamp_to_timestr(timestamp):
tre_timeArray = time.localtime(timestamp)
return time.strftime("%Y-%m-%d %H:%M:%S", tre_timeArray)
print(timestamp_to_timestr(timestamp))
2023-07-05 17:09:27
首先,获得对应的时间:
timestr = "2023-07-05 17:09:27.190377"
然后,编写转化为时间戳的函数,转化只用到 time 库:
def timestr_to_timestamp(timestr):
timestr1, timestr2 = timestr.split('.')
struct_time = time.strptime(timestr1, '%Y-%m-%d %H:%M:%S')
seconds = time.mktime(struct_time)
millseconds = float("0." + timestr2)
return seconds + millseconds
print(timestr_to_timestamp(timestr))
# 1688548167.190377
要获得以毫秒计时的时间戳,只需要把 return 值改为 int((seconds + millseconds) * 1000) 即可!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。