将日期时间格式化为字符串(以毫秒为单位)

我想datetime从日期起以毫秒为单位的字符串。这段代码对我来说很典型,我很想学习如何缩短它。


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


慕斯王
浏览 746回答 3
3回答

MMTTMM

要获取一个以毫秒为单位的日期字符串(秒后3个小数位),请使用以下命令:from datetime import datetimeprint datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]>>>> OUTPUT >>>>2020-05-04 10:18:32.926

蛊毒传说

在某些系统上,微秒格式%f可能会给出"0",因此简单地切掉最后三个字符不是可移植的。以下代码精心设置了以毫秒为单位的时间戳记格式:from datetime import datetime(dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')dt = "%s.%03d" % (dt, int(micro) / 1000)print dt示例输出:2016-02-26 04:37:53.133为了获得OP想要的确切输出,我们必须去除标点符号:from datetime import datetime(dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.')dt = "%s%03d" % (dt, int(micro) / 1000)print dt示例输出:20160226043839901
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python