You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Epoch时间戳转换为带毫秒的标准时间格式?

问题:保留Epoch时间戳转换后的毫秒部分

我有一份包含Epoch时间戳的日志文件,内容示例如下:

...
1668516788.901393
1668516788.902532
1668516788.911157
1668516788.921403
1668516788.922577
...

我需要将其转换为如下格式的时间:
15 Nov 2022, 18:25:31.256

我使用了以下代码:

mytime = time.asctime(time.localtime(float(mytime)))

得到的输出为Tue Nov 15 12:53:08 2022,但该结果缺失了毫秒部分。请问有没有办法保留时间中的毫秒部分?


解决方法

time.asctime()本身不支持保留毫秒,你需要拆分时间戳的秒数和毫秒部分分别处理,再拼接成目标格式。

方案1:基于time模块手动拼接

import time

# 读取日志中的时间戳字符串
timestamp_str = "1668516788.901393"
timestamp = float(timestamp_str)

# 拆分秒数和毫秒数(取三位)
total_seconds = int(timestamp)
milliseconds = int((timestamp - total_seconds) * 1000)

# 格式化日期时间主体
date_time = time.strftime("%d %b %Y, %H:%M:%S", time.localtime(total_seconds))

# 拼接毫秒得到最终格式
formatted_time = f"{date_time}.{milliseconds:03d}"
print(formatted_time)

输出示例:15 Nov 2022, 12:53:08.901

方案2:使用datetime模块简化操作

datetime模块可以直接解析带毫秒的时间戳,通过格式化字符串快速实现需求:

from datetime import datetime

timestamp_str = "1668516788.901393"
timestamp = float(timestamp_str)

# %f 输出6位微秒,[:-3]截取前3位转为毫秒
formatted_time = datetime.fromtimestamp(timestamp).strftime("%d %b %Y, %H:%M:%S.%f")[:-3]
print(formatted_time)

输出结果与方案1一致:15 Nov 2022, 12:53:08.901

注意事项

  • %b会生成英文月份缩写(如Nov),完全匹配你需要的格式;若需中文月份,可替换为%m后自行映射月份名称。
  • 两种方案均能保证毫秒部分的准确性,可根据代码习惯选择使用。

内容的提问来源于stack exchange,提问作者Fasih

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:00:20