问题:将日期时间格式化为字符串(以毫秒为单位)
我想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
回答 0
要获取带有毫秒的日期字符串(秒后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])
回答 1
使用Python 3.6,您可以使用:
from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
输出:
'2019-05-10 09:08:53.155'
此处提供更多信息:https : //docs.python.org/3/library/datetime.html#datetime.datetime.isoformat
回答 2
print datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
回答 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
为了获得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
回答 4
大概是这样的:
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.
回答 5
我假设您的意思是您正在寻找比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
回答 6
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:]
使用转换()和切片方法在同一时间运行
转换()呈现优点是在一条线可用
在第一个基础上比较时间:
1.000 * t.strftime(’%Y%m%d %% H%M%S%f’)
0.351 * str(t).replace(’-‘,”)。replace(’:’,”)。replace(’。’,”)。replace(”,”)
0.198 * str(t).translate(无,’-:.’)
0.194 * s [:4] + s [5:7] + s [8:10] + s [11:13] + s [14:16] + s [17:19] + s [20:]
回答 7
我处理了同样的问题,但就我而言,重要的是毫秒是四舍五入而不是被截断的
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]
回答 8
import datetime
# convert string into date time format.
str_date = '2016-10-06 15:14:54.322989'
d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f')
print(d_date)
print(type(d_date)) # check d_date type.
# convert date time to regular format.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
<<<<<<输出>>>>>>>
2016-10-06 15:14:54.322989
<class 'datetime.datetime'>
06 October 2016 03:14:54 PM
2016-10-06 03:14:54 PM
2016-10-06 15:14:54
回答 9
python -c "from datetime import datetime; print str(datetime.now())[:-3]"
2017-02-09 10:06:37.006
回答 10
datetime
t = datetime.datetime.now()
ms = '%s.%i' % (t.strftime('%H:%M:%S'), t.microsecond/1000)
print(ms)
14:44:37.134
回答 11
问题所在 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"
动态构建所需的小数位数。