datetime:舍入/修剪位数,以微秒为单位 [英] datetime: Round/trim number of digits in microseconds
问题描述
目前,我正在记录内容,并且正在使用带有自定义 formatTime()
的我自己的格式化程序:
Currently I am logging stuff and I am using my own formatter with a custom formatTime()
:
def formatTime(self, _record, _datefmt):
t = datetime.datetime.now()
return t.strftime('%Y-%m-%d %H:%M:%S.%f')
我的问题是微秒,%f
是六位数字。无论如何,是否需要吐出更少的数字,例如微秒的前三位?
My issue is that the microseconds, %f
, are six digits. Is there anyway to spit out less digits, like the first three digits of the microseconds?
推荐答案
最简单的方法是使用切片仅截去微秒的最后三位数字:
The simplest way would be to use slicing to just chop off the last three digits of the microseconds:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
我强烈建议您切碎。我曾经写过一些日志代码,将时间戳四舍五入而不是四舍五入,当四舍五入改变最后一位时,我发现它实际上有点令人困惑。定时代码在某个时间戳记时停止运行,但是由于舍入的缘故,存在带有该时间戳记的日志事件。
I strongly recommend just chopping. I once wrote some logging code that rounded the timestamps rather than chopping, and I found it actually kind of confusing when the rounding changed the last digit. There was timed code that stopped running at a certain timestamp yet there were log events with that timestamp due to the rounding. Simpler and more predictable to just chop.
如果您想真正地舍入数字而不是仅仅进行切碎,则需要更多的工作但并不可怕:
If you want to actually round the number rather than just chopping, it's a little more work but not horrible:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
head = s[:-7] # everything up to the '.'
tail = s[-7:] # the '.' and the 6 digits after it
f = float(tail)
temp = "{:.03f}".format(f) # for Python 2.x: temp = "%.3f" % f
new_tail = temp[1:] # temp[0] is always '0'; get rid of it
return head + new_tail
显然,您可以使用较少的变量来简化上述操作;我只是希望它很容易理解。
Obviously you can simplify the above with fewer variables; I just wanted it to be very easy to follow.
这篇关于datetime:舍入/修剪位数,以微秒为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!