strftime 无法格式化微秒。
strftime (String Format Time) 的格式化代码是由 C 标准库定义的,其标准代码集中没有专门用于微秒的格式说明符。
为什么 strftime 不支持微秒?
strftime 主要用于将时间格式化为人类可读的字符串,其设计初衷是处理到秒级别,对于更高精度的时间单位(如微秒、纳秒),通常需要专门的工具来处理,或者进行一些技巧性的转换。
如何在 Python 中正确处理和显示微秒?
既然 strftime 不行,我们有以下几种非常有效的方法来处理微秒。
使用 strptime 和 strftime 的组合(推荐)
这是最常用、最优雅的“曲线救国”方法,原理是:
- 用
strftime格式化到秒的部分。 - 单独获取微秒部分。
- 将它们拼接起来。
示例代码:
import datetime
# 1. 创建一个包含微秒的时间对象
now = datetime.datetime.now()
# 2. 使用 strftime 格式化到秒的部分
# %Y-%m-%d %H:%M:%S 是常见的格式
time_str_without_microseconds = now.strftime('%Y-%m-%d %H:%M:%S')
# 3. 获取微秒部分 (now.microsecond)
# 使用 f-string 或 .format() 进行格式化,确保微秒始终是6位数
time_str_with_microseconds = f"{time_str_without_microseconds}.{now.microsecond:06d}"
print(now)
print(time_str_with_microseconds)
输出可能如下:
2025-10-27 10:30:45.123456
2025-10-27 10:30:45.123456
f"{now.microsecond:06d}"是一个很棒的技巧:06d表示将数字格式化为至少6位宽的十进制数。- 如果微秒是
123,它会显示为000123。 - 如果微秒是
123456,它会显示为123456。 - 这保证了时间戳的格式统一。
直接使用 str() 或 f-string(最简单)
对于大多数简单的日志记录或显示需求,直接将 datetime 对象转换为字符串是最简单的方法,Python 的默认字符串表示已经包含了微秒。
示例代码:
import datetime
now = datetime.datetime.now()
# 直接打印 datetime 对象
print(now)
# 使用 f-string
print(f"当前时间: {now}")
输出:
2025-10-27 10:30:45.123456
当前时间: 2025-10-27 10:30:45.123456
优点:
- 极其简单,一行代码搞定。
- 格式标准,易于阅读。
缺点:
- 格式是固定的,如果你想自定义格式(用
T分隔日期和时间),这种方法就不行了。
使用 isoformat() 方法(适用于 API 和日志)
datetime 对象有一个 isoformat() 方法,它返回一个符合 ISO 8601 标准的字符串,这个标准本身就支持纳秒级精度,当然也包括微秒。
示例代码:
import datetime now = datetime.datetime.now() # 使用 isoformat(),它会自动包含微秒 iso_time_str = now.isoformat() print(iso_time_str) # 你也可以指定 timespec 来控制秒的精度 iso_time_str_with_ms = now.isoformat(timespec='milliseconds') # 只显示到毫秒 print(iso_time_str_with_ms)
输出:
2025-10-27T10:30:45.123456
2025-10-27T10:30:45.123
优点:
- 标准化,非常适合用于 API 请求、数据交换和日志系统。
- 可以通过
timespec参数灵活控制精度('auto', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds')。
格式化代码速查表
为了方便你参考,这里列出 strftime 中最常用的格式代码:
| 代码 | 描述 | 示例 |
|---|---|---|
%Y |
4位数的年份 | 2025 |
%m |
2位数的月份 (01-12) | 10 |
%d |
2位数的日期 (01-31) | 27 |
%H |
24小时制的小时 (00-23) | 10 |
%M |
分钟 (00-59) | 30 |
%S |
秒 (00-59) | 45 |
%f |
微秒 (000000-999999) | 123456 |
%F |
%Y-%m-%d 的简写 |
2025-10-27 |
%T |
%H:%M:%S 的简写 |
10:30:45 |
%z |
UTC 偏移量 (e.g., +0800) | +0800 |
%Z |
时区名称 | CST |
注意: %f 是 datetime 对象的 strftime 方法的一个扩展,它不是标准 C 库的一部分,这意味着它在所有 Python 实现上都能工作,但在其他语言或一些严格的 C 库环境中可能不可用。
| 需求 | 推荐方法 | 示例 |
|---|---|---|
| 简单显示或日志 | 直接 str() 或 f-string |
print(now) |
| 生成标准化的时间戳(如API) | isoformat() |
now.isoformat() |
| 需要高度自定义格式(含微秒) | strftime + f-string 拼接 |
now.strftime('%H:%M:%S') + f".{now.microsecond:06d}" |
| 检查是否支持微秒格式 | 使用 %f |
now.strftime('%Y-%m-%d %H:%M:%S.%f') |
strftime 本身不直接支持微秒,但通过组合使用 Python 的其他字符串格式化工具,可以非常灵活和方便地实现你的目标。
