在 Python 中,你可以使用 datetime
模块来格式化输出时间,并通过 strftime
方法控制时间的显示格式。如果你需要控制时间的精度(例如毫秒或微秒),可以通过格式化字符串来实现。
以下是一些常见的用法:
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
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
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
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
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 中的时间输出精度!