datetime:舍入修剪位数,以微秒为单位

datetime:舍入修剪位数,以微秒为单位,第1张

datetime:舍入/修剪位数,以微秒为单位

最简单的方法是使用切片将微秒的最后三位数字切掉:

def format_time():    t = datetime.datetime.now()    s = t.strftime('%Y-%m-%d %H:%M:%S.%f')    return s[:-3]

我强烈建议切碎。我曾经写过一些对时间戳进行四舍五入而不是四舍五入的记录代码,当四舍五入改变了最后一位时,我发现它实际上有点令人困惑。定时代码在某个时间戳记时停止运行,但是由于舍入的缘故,存在带有该时间戳记的日志事件。切碎更简单,更可预测。

如果您想实际舍入数字而不是仅切碎,则需要做更多的工作,但并不可怕:

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

显然,您可以使用更少的变量来简化上述 *** 作;我只是希望它很容易遵循。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5646011.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存