我希望从日期开始有一个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 :(得分:257)
要获取具有毫秒(秒后3位小数)的日期字符串,请使用:
from datetime import datetime
print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
>>>> OUTPUT >>>>
2018-10-04 10:18:32.926
答案 1 :(得分:17)
print datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
答案 2 :(得分:10)
@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
答案 3 :(得分:3)
使用Python 3.6,您可以使用:
e<ng-template ngFor let-item [ngForOf]="folios">
<tr *ngIf="item.shares >0" [ngClass]="{'table-success': item.gainPercent >5,'table-danger': item.gainPercent <-5}">e
输出:
from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
此处有更多信息:https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat
答案 4 :(得分:2)
我认为你的意思是你正在寻找比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
答案 5 :(得分:2)
可能是这样的:
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.
答案 6 :(得分:1)
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()和切片方法 translate()提供了可在一行中使用的优势
在第一个基础上比较时间:
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 :(得分:1)
I dealt with the same problem but in my case it was important that the millisecond was rounded and not truncated
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 :(得分:1)
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)
&LT;&LT;&LT;&LT;&LT;&LT; OUTPUT&gt;&gt;&gt;&gt;&gt;&gt;&gt;
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 :(得分:1)
python -c "from datetime import datetime; print str(datetime.now())[:-3]"
2017-02-09 10:06:37.006
答案 10 :(得分:0)
datetime
t = datetime.datetime.now()
ms = '%s.%i' % (t.strftime('%H:%M:%S'), t.microsecond/1000)
print(ms)
14:44:37.134
答案 11 :(得分:0)
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"
。
答案 12 :(得分:0)
在python 3.6及更高版本中,使用python f-strings:
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)}
格式字符串{:03d}
和毫秒到毫秒的转换// 1000
来自https://github.com/python/cpython/blob/master/Lib/datetime.py中用于datetime.datetime.isoformat()的def _format_time
。
答案 13 :(得分:0)
如果您准备将时间存储在变量中并进行一些字符串操作,那么您实际上可以在不使用 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 时需要省略括号)。