将日期时间格式化为以毫秒为单位的字符串 [英] Format a datetime into a string with milliseconds

查看:37
本文介绍了将日期时间格式化为以毫秒为单位的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有毫秒的日期的 datetime 字符串.这段代码对我来说很典型,我很想学习如何缩短它.

I want to have a datetime string from the date with milliseconds. This code is typical for me and I'm eager to learn how to shorten it.

from datetime import datetime

timeformatted= str(datetime.utcnow())
semiformatted= timeformatted.replace("-","")
almostformatted= semiformatted.replace(":","")
formatted=almostformatted.replace(".","")
withspacegoaway=formatted.replace(" ","")
formattedstripped=withspacegoaway.strip()
print formattedstripped

推荐答案

要获取以毫秒为单位的日期字符串(秒后三位小数),请使用:

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

>>>> OUTPUT >>>>
2020-05-04 10:18:32.926

注意:对于 Python3,print 需要括号:

Note: For Python3, print requires parentheses:

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

这篇关于将日期时间格式化为以毫秒为单位的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆