如何将datetime对象格式化为带有毫秒的字符串?


当前回答

使用Python 3.6+,你可以设置isoformat的timespec:

>>> from datetime import datetime
>>> datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
'2019-05-10 09:08:53.155'

其他回答

我假设您的意思是您正在寻找比datetime.datetime.strftime()更快的东西,并且实际上是从utc时间戳中剥离非alpha字符。

你的方法稍微快一点,我认为你可以通过切片字符串来加快速度:

>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267

>>> def replaceutc(s):
...     return s\
...         .replace('-','') \
...         .replace(':','') \
...         .replace('.','') \
...         .replace(' ','') \
...         .strip()
... 
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067

>>> def sliceutc(s):
...     return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
... 
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694
from datetime import datetime
from time import clock

t = datetime.utcnow()
print 't == %s    %s\n\n' % (t,type(t))

n = 100000

te = clock()
for i in xrange(1):
    t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"

print

te = clock()
for i in xrange(1):
    t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"

print

te = clock()
for i in xrange(n):
    t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"

print

te = clock()
for i in xrange(n):
    s = str(t)
    t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] 
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "

结果

t == 2011-09-28 21:31:45.562000    <type 'datetime.datetime'>


3.33410112179
20110928212155046000  t.strftime('%Y%m%d%H%M%S%f')

1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.658806915404
20110928212130453000 str(t).translate(None,' -:.')

0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

translate()和slicing方法的使用同时运行 Translate()的优点是可以在一行中使用

在第一个的基础上比较时间:

1.000 * t.strftime('%Y%m%d%H% m% S%f') 0.351 * str (t) .replace(‘-’,”).replace(‘:’,”).replace(‘。’,”).replace (' “,”) 0.198 * str(t)。翻译(,):。) 0.194 * s[4] +[7] +[8:10] +年代[11:13]+[十四16]+年代(十七19)+ 年代(20:)

datetime
t = datetime.datetime.now()
ms = '%s.%i' % (t.strftime('%H:%M:%S'), t.microsecond/1000)
print(ms)
14:44:37.134

要获得以毫秒为单位的日期字符串,使用[:-3]修剪%f(微秒)的最后三位数字:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

或者稍短一点:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]

在python 3.6及以上版本中使用python f-strings:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)

print(f"{dt:%Y-%m-%d %H:%M:%S}.{dt.microsecond // 1000:03d}")

特定于格式化毫秒的代码是:

{dt.microsecond // 1000:03d}

格式字符串{:03d}和微秒到毫秒的转换// 1000来自https://github.com/python/cpython/blob/master/Lib/datetime.py中的def _format_time,用于datetime.datetime.isoformat()。