美文网首页
python 输出格式化本地时间 精确到毫秒

python 输出格式化本地时间 精确到毫秒

作者: 浊酒江湖 | 来源:发表于2023-10-20 22:50 被阅读0次

要输出格式化的本地时间并精确到毫秒,可以使用strftime函数来格式化时间字符串,然后使用datetime.now()函数获取当前本地时间,最后使用strftime函数来格式化毫秒部分。

下面是一个示例代码:

from datetime import datetime

now = datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted_time)

输出示例

2022-06-01 12:34:56.789123

在上面的例子中,%f用于格式化毫秒部分。请注意,%f会输出6位的微秒,所以如果你只需要3位毫秒,可以使用[:-3]来截取字符串的前面3位。例如:

formatted_time = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

这将输出:

2022-06-01 12:34:56.789

相关文章

网友评论

      本文标题:python 输出格式化本地时间 精确到毫秒

      本文链接:https://www.haomeiwen.com/subject/orclidtx.html