将datetime格式化为具有毫秒的字符串
问题描述:
我希望从毫秒的日期开始一个 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
答
OP要求一个带毫秒的字符串(后面3位小数)秒)。要获取毫秒数,请改用:
The OP asked for a string with milliseconds (3 decimal places behind seconds). To get milliseconds, use this instead:
from datetime import datetime
print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
>>>> OUTPUT >>>>
2013-08-23 10:18:32.926