【问题标题】:Formatting microseconds to two decimal places (in fact converting microseconds into tens of microseconds)将微秒格式化为小数点后两位(实际上是将微秒转换为几十微秒)
【发布时间】:2014-10-27 11:51:02
【问题描述】:

我正在使用以下打印时间戳:

strftime('%d-%m-%Y %H:%M:%S.%f')

但是,我想将微秒四舍五入到小数点后两位,而不是打印到小数点后六位。有没有更简单的方法来实现这一点,而不是“解包”所有时间元素,将微秒格式化并舍入到小数点后 2 位,然后格式化新的“打印字符串”?

【问题讨论】:

  • 这些是datetime 实例吗?

标签: python python-2.7 datetime


【解决方案1】:

你必须把自己围起来;使用字符串格式化格式化不带微秒的日期,然后分别添加microsecond属性的前两位数字:

'{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond / 10000.0)

演示:

>>> from datetime import datetime
>>> dt = datetime.now()
>>> '{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond / 10000.0)
'27-10-2014 11:56:32.72'

【讨论】:

  • 已经这样做了。不禁感觉秒作为浮点数将是 datetime() 的有用补充。
【解决方案2】:
decimal_places = 2
ndigits = decimal_places - 6
assert ndigits < 0
d = d.replace(microsecond=round(d.microsecond, ndigits))
print(d.strftime('%d-%m-%Y %H:%M:%S.%f')[:ndigits])
# -> 2014-10-27 11:59:53.87

【讨论】:

    【解决方案3】:

    根据 jfs 的回答,我又添加了一条语句

    replace(microsecond=round(d.microsecond, ndigits))

    可能会报错:ValueError: microsecond must be in 0..999999

    即如果微秒是从 995000 到 999999,round(microsecond, ndigits) 将给出 1000000。

    d = datetime.utcfromtimestamp(time.time())
    decimal_places = 2
    ndigits = decimal_places - 6
    r = round(d.microsecond, ndigits)
    if r > 999999:
        r = 999999
    d = d.replace(microsecond=r)
    ts = d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:ndigits]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      相关资源
      最近更新 更多