杰瑞科技汇

Python中如何用strftime格式化毫秒?

在 Python 中,strftime 方法本身不支持直接格式化毫秒,这是因为 strftime 依赖于底层 C 库的实现,而标准 C 库的 strftime 函数通常只精确到秒。

Python中如何用strftime格式化毫秒?-图1
(图片来源网络,侵删)

有几种常见的方法可以在 Python 中获取包含毫秒的时间字符串。

使用 strptimestrftime 的组合(推荐)

这是最常用且最稳健的方法,它利用 datetime 对象本身就包含微秒(毫秒是微秒的千分之一)这一特性。

  1. 获取一个包含微秒的 datetime 对象。
  2. 使用 strftime 格式化大部分时间部分。
  3. 手动从 datetime 对象中提取微秒部分,并将其格式化为三位数的毫秒,然后拼接起来。
import datetime
# 1. 获取当前的 datetime 对象,它包含了微秒信息
now = datetime.datetime.now()
# 2. 使用 strftime 格化到秒
time_string_without_ms = now.strftime("%Y-%m-%d %H:%M:%S")
# 3. 提取微秒部分,并格式化为三位数的毫秒
#    - now.microsecond 获取微秒值 (0 - 999999)
#    - {:03d} 将其格式化为三位数,前面补零
milliseconds = now.microsecond // 1000  # 将微秒转换为毫秒
milliseconds_str = f"{milliseconds:03d}"
# 4. 拼接起来
time_string_with_ms = f"{time_string_without_ms}.{milliseconds_str}"
print(f"当前时间 (带毫秒): {time_string_with_ms}")
# 也可以在一行内完成
one_liner = now.strftime("%Y-%m-%d %H:%M:%S") + f".{now.microsecond // 1000:03d}"
print(f"单行实现: {one_liner}")

输出示例:

当前时间 (带毫秒): 2025-10-27 15:30:45.123
单行实现: 2025-10-27 15:30:45.123

直接使用 f-string (Python 3.6+)

如果你只是想简单地显示时间,f-string 提供了最简洁、最易读的方式。datetime 对象的 f 格式说明符可以直接格式化时间,并且默认包含毫秒。

Python中如何用strftime格式化毫秒?-图2
(图片来源网络,侵删)
import datetime
now = datetime.datetime.now()
# 使用 f-string 的 'f' 格式说明符
# 它会自动将微秒格式化为 6 位数字 (123456)
# 我们只需要取前三位即可
time_string_with_ms = f"{now:%Y-%m-%d %H:%M:%S}.{now.microsecond // 1000:03d}"
# 或者更直接,f-string 会处理微秒,我们只需要截取前三位
# 注意:这种方式会多一个点,所以我们需要替换掉多余的点
time_string_fstring = f"{now:%Y-%m-%d %H:%M:%S.%f}"
# time_string_fstring 的格式是 '2025-10-27 15:30:45.123456'
# 截取前 23 个字符 (到秒) + 3 个毫秒字符
time_string_with_ms_fstring = time_string_fstring[:-3]
print(f"f-string 方法: {time_string_with_ms_fstring}")

输出示例:

f-string 方法: 2025-10-27 15:30:45.123

这种方法非常优雅,但需要理解 f-string 的时间格式化能力。


使用 time 模块

time 模块的 time() 函数返回一个浮点数,其中小数部分代表秒(可以转换为毫秒)。

import time
# 获取当前时间戳,包含小数部分(秒)
current_time = time.time()
# 将时间戳转换为 struct_time
# time.localtime() 返回一个不包含毫秒/微秒的 struct_time 对象
struct_time = time.localtime(current_time)
# 使用 strftime 格式化到秒
time_string_without_ms = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
# 计算毫秒部分
# current_time 的小数部分 * 1000 并四舍五入取整
milliseconds = int(round((current_time - int(current_time)) * 1000))
# 拼接起来
time_string_with_ms = f"{time_string_without_ms}.{milliseconds:03d}"
print(f"time 模块方法: {time_string_with_ms}")

输出示例:

Python中如何用strftime格式化毫秒?-图3
(图片来源网络,侵删)
time 模块方法: 2025-10-27 15:30:45.456

总结与对比

方法 优点 缺点 推荐场景
strftime + 手动拼接 最稳健、清晰,不依赖 Python 版本,易于理解。 代码稍长,需要两步操作。 通用推荐,特别是需要兼容旧版 Python 或代码需要清晰可读时。
f-string 最简洁、最 Pythonic,代码量最少。 需要 Python 3.6+,对 f-string 格式化不熟悉的人可能觉得不直观。 现代 Python (3.6+) 下的首选,代码追求简洁时。
time 模块 直接处理浮点数时间戳。 逻辑比 datetime 方法稍复杂,time.localtime 会丢失微秒精度,需要自己计算。 当你已经在使用 time 模块,或者需要从浮点时间戳开始处理时。

对于绝大多数情况,方法一 (strftime + 手动拼接) 是最可靠和推荐的选择,如果你使用的是 Python 3.6 或更高版本,方法二 (f-string) 是一个非常优秀且现代的替代方案。

分享:
扫描分享到社交APP
上一篇
下一篇