插件窝 干货文章 Python 中如何格式化输出时间并控制精度

Python 中如何格式化输出时间并控制精度

time 时间 格式化 输出 868    来源:    2025-03-14

在 Python 中,你可以使用 datetime 模块来格式化输出时间,并通过 strftime 方法控制时间的显示格式。如果你需要控制时间的精度(例如毫秒或微秒),可以通过格式化字符串来实现。

以下是一些常见的用法:

1. 基本时间格式化

from datetime import datetime

# 获取当前时间
now = datetime.now()

# 格式化输出时间
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)

输出示例:

2023-10-05 14:30:45

2. 控制时间精度(毫秒、微秒)

from datetime import datetime

# 获取当前时间
now = datetime.now()

# 格式化输出时间,包含毫秒
formatted_time_with_ms = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted_time_with_ms)

# 如果只需要毫秒的前三位,可以截取字符串
formatted_time_with_ms_3 = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
print(formatted_time_with_ms_3)

输出示例:

2023-10-05 14:30:45.123456
2023-10-05 14:30:45.123

3. 控制时间精度(微秒)

from datetime import datetime

# 获取当前时间
now = datetime.now()

# 格式化输出时间,包含微秒
formatted_time_with_us = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted_time_with_us)

输出示例:

2023-10-05 14:30:45.123456

4. 使用 time 模块格式化时间

import time

# 获取当前时间戳
current_time = time.time()

# 格式化输出时间
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time))
print(formatted_time)

输出示例:

2023-10-05 14:30:45

5. 使用 time 模块控制精度

import time

# 获取当前时间戳
current_time = time.time()

# 格式化输出时间,包含毫秒
formatted_time_with_ms = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time)) + f".{int(current_time * 1000) % 1000:03d}"
print(formatted_time_with_ms)

输出示例:

2023-10-05 14:30:45.123

总结

  • 使用 strftime 方法可以灵活地格式化时间。
  • 通过 %f 可以输出微秒部分,截取字符串可以控制精度。
  • 如果需要更高精度的时间处理,可以使用 time 模块结合时间戳来实现。

希望这些方法能帮助你更好地控制 Python 中的时间输出精度!