在Python中获取毫秒级时间,你可以使用以下方法:
1. 使用 `time` 模块:
import time获取当前时间戳,单位是秒timestamp_seconds = time.time()转换为毫秒级时间戳timestamp_milliseconds = int(timestamp_seconds * 1000)print("当前时间戳(毫秒):", timestamp_milliseconds)
2. 使用 `datetime` 模块:

from datetime import datetime获取当前日期时间对象now = datetime.now()转换为时间戳(秒)timestamp_seconds = time.mktime(now.timetuple())转换为毫秒级时间戳timestamp_milliseconds = int(timestamp_seconds * 1000)print("当前时间戳(毫秒):", timestamp_milliseconds)
3. 使用 `datetime` 模块直接获取包含毫秒的时间字符串:
from datetime import datetime获取当前日期时间,包含毫秒formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] 去掉最后三位微秒部分print("当前时间(含毫秒):", formatted_time)
