python获取当前时间到毫秒

获取当前时间到毫秒可以在获取当前时间的基础上,再使用strftime方法来将当前时间格式化成带有毫秒的字符串。具体代码如下:

import datetime

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

# 格式化输出带有毫秒的当前时间字符串
current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
print(current_time_str)

上述代码通过在格式化字符串中添加"%f"来获取毫秒,说明%f代表的是毫秒,在格式化输出时,需要使用[3:-3]来截取掉字符串中的微秒.运行以上代码,会输出当前时间,并将其格式化为"年-月-日 时:分:秒.毫秒"的字符串格式。

你可能感兴趣的:(python)