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

Python 将日期时间格式化为以毫秒为单位的字符串,python,datetime,string-formatting,Python,Datetime,String Formatting,我想要一个日期的datetime字符串,以毫秒为单位。这段代码对我来说很典型,我渴望学习如何缩短它 from datetime import datetime timeformatted= str(datetime.utcnow()) semiformatted= timeformatted.replace("-","") almostformatted= semiformatted.replace(":","") formatted=almostformatted.replace(".","

我想要一个日期的
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

我猜您的意思是,您正在寻找比datetime.datetime.strftime()更快的东西,并且基本上从utc时间戳中去除了非字母字符

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

>>> 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
结果

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:]
t==2011-09-2821:31:45.562000
3.33410112179
2011092822155046000吨标准时间(“%Y%m%d%H%m%S%f”)
1.17067364707
2011092822130453000 str(t).替换('-','').替换(':','').替换('.','').替换('.','')
0.658806915404
2011092821301453000 str(t).翻译(无,,-:.)
0.645189262881
201109282123053000 s[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+s[20:]
使用translate()切片方法同时运行
translate()提供了在一行中可用的优势

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

1.000*t.strftime(“%Y%m%d%H%m%S%f”)

0.351*str(t).替换('-','').替换(':','').替换('.','').替换('.','').替换(' “,”)

0.198*str(t).翻译(无,,-:。)

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


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

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
需要括号:

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
可能是这样的:

import datetime
now = datetime.datetime.now()
now.strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]  
# [:-3] => Removing the 3 last characters as %f is for microsecs.

我处理了同样的问题,但在我的例子中,毫秒是四舍五入的,而不是截断的,这一点很重要

from datetime import datetime, timedelta

def strftime_ms(datetime_obj):
    y,m,d,H,M,S = datetime_obj.timetuple()[:6]
    ms = timedelta(microseconds = round(datetime_obj.microsecond/1000.0)*1000)
    ms_date = datetime(y,m,d,H,M,S) + ms
    return ms_date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

@Cabbi提出了一个问题,即在某些系统上,微秒格式的
%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
20160226043839901
为了获得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
示例输出:

2016-02-26 04:37:53.133
20160226043839901
>>

2016-10-06 15:14:54.322989
2016年10月6日下午03:14:54
2016-10-06 03:14:54下午
2016-10-06 15:14:54
日期时间
t=datetime.datetime.now()
ms='%s.%i'(t.strftime('%H:%M:%s'),t.微秒/1000)
打印(毫秒)
14:44:37.134

对于Python 3.6,您可以使用:

from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
输出:

'2019-05-10 09:08:53.155'

这里有更多信息:

datetime.utcnow()和其他类似解决方案的问题是速度慢

更有效的解决方案可能如下所示:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s
其中,在您的情况下,
prec
将是
3
(毫秒)

该函数最多可使用9位小数(请注意第二个格式字符串中的数字
9


如果您想对小数部分进行四舍五入,我建议使用所需的小数位数动态构建
“%.9f”

在python 3.6及更高版本中使用:

特定于毫秒格式的代码为:

{"{:03d}".format(i.microsecond // 1000)}

格式字符串
{:03d}
和微秒到毫秒的转换
//1000
来自
def\u format\u time
,用于。如果您准备将时间存储在变量中并执行一些字符串操作,那么实际上可以不使用datetime模块来执行此操作

>>> _now = time.time()
>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.3f'%_now).split('.')[1])) # Rounds to nearest millisecond
Time : 05/02/21 01:16:58.676

>>> 
%.3f将四舍五入到最接近的毫秒,如果您想要更高或更低的精度,只需更改小数位数

>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.1f'%_now).split('.')[1])) # Rounds to nearest tenth of a second
Time : 05/02/21 01:16:58.7

>>>


在Python 2.7和3.7中进行了测试(显然,在2.x版中调用print时,您需要省去括号)。

请写一个标题来描述您的问题,并尽量使您的问题清晰、中肯。这里值得一提的是,额外的精度通常很好。例如,Java的
Instant.parse
可以解析使用
strftime(“%Y-%m-%dT%H:%m:%s.%fZ”)创建的表示形式。
Nice!这在不牺牲性能的情况下确实更干净。str.translate()在我的测试中实际上更快了。@oxtopus做得很好。就我个人而言,我不再使用timeit来简单地测量时间。奇怪的是,您的代码1-0.67-0.53和我的代码1-0.35-0.20的时间比率不同,对于strftime-replace-slicingMaybe方法,在每次测试迭代中调用str(datetime.datetime.utcnow())与设置它一次有关?仅供参考,这会打印微秒作为最后6位数字。将
[:-3]
添加到末尾,删除最后3位数字,使其仅显示毫秒。微秒可以小于6位,因此[:-3]打印出错误的毫秒如果我们有时区怎么办@ᐅdevrimbaris for timezone checkout Lorenzo的回答注意,如果您想使用
导入日期时间
而不是
从日期时间导入日期时间
,则必须使用以下命令:
datetime.datetime.utcnow().strftime(%H:%M:%s.%f”)
,如果微秒为0,在windows 2.7实现中,微秒不会打印出来,因此它会缩短秒数:(@cabbi,您可以使用它:
(dt,micro)=datetime.utcnow().strftime(“%Y-%m-%d%H:%m:%S.%f”).split(“);dt=“%S.%03d%”(dt,int(micro)/1000);print dt
。我添加了这个作为答案。请注意,这会截断,而不是像gens提到的那样舍入到毫秒,这不会弄错吗?它的第一个drops数字是>=5?。事实上,如果usec部分是>999500,那么你将永远不会通过摆弄微秒部分来获得正确的时间。我实际上正在做的是:print'%s.%03d'(dt.strftime(%Y-%m-%d%H:%m:%S),int(dt.微秒/1000))同意@cabbi,不需要使用字符串来回转换,也不需要使用时区进行直观转换:date=datetime(2019,5,10)date_与_tz=pytz.timezone('Europe/Rome')。本地化(date)date_与_tz.isoformat(sep='T',timespec='毫秒)输出:'2019-05-10T00:00.000+02:00'
from datetime import datetime 

i = datetime.utcnow()

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

{"{:03d}".format(i.microsecond // 1000)}
>>> _now = time.time()
>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.3f'%_now).split('.')[1])) # Rounds to nearest millisecond
Time : 05/02/21 01:16:58.676

>>> 
>>> print ("Time : %s.%s\n" % (time.strftime('%x %X',time.localtime(_now)),
... str('%.1f'%_now).split('.')[1])) # Rounds to nearest tenth of a second
Time : 05/02/21 01:16:58.7

>>>