【问题标题】:How to round up (always) time to nearest ten?如何将(总是)时间四舍五入到最接近的十?
【发布时间】:2015-09-17 09:27:24
【问题描述】:

我不想冒险为此提出破解,因为它涉及datetime 对象。基本上,我想按如下方式进行转换:

2010-04-21 06:37:53 -> 2010-04-21 06:40:00
2010-08-26 02:54:00 -> 2010-08-26 03:00:00
2010-04-21 06:37:12 -> 2010-04-21 06:40:00
2010-08-26 11:54:19 -> 2010-08-27 00:00:00

有内置的方法吗?

【问题讨论】:

  • 2010-08-26 11:50:00.001 怎么样?应该是11:50 还是12:00 出来?
  • 哦..我正在丢弃微秒。所以这个应该到11:50

标签: python datetime date


【解决方案1】:

您需要将您的时间转换为 unix 时间戳,并根据需要对时间戳进行四舍五入。

round(Timestamp / 60 seconds [minutes conversion] / 10 [round precision]) * 60 * 10 [to get the timestamp back]

【讨论】:

    【解决方案2】:

    您只想四舍五入。即使忽略秒和微秒,您也会得到正确答案。

    在这种情况下,这是一个班轮:

    def round_minutes(t): # t is a datetime object
        return t - datetime.timedelta( minutes = t.minute - round(t.minute, -1), seconds = t.second, microseconds = t.microsecond)
    

    您将原始分钟和四舍五入分钟之间的时间差取到最接近的 10 并应用该差值。此外,对于 zerofy 秒和微秒,您也可以将它们添加到 delta 中。

    【讨论】:

      【解决方案3】:

      这似乎对我有用。

      def round_up(tm):
          upmins = math.ceil(float(tm.minute)/10)*10
          diffmins = upmins - tm.minute
          newtime = tm + datetime.timedelta(minutes=diffmins)
          newtime = newtime.replace(second=0)
          return newtime
      

      转化次数:

      2010-04-21 06:37:53 -> 2010-04-21 06:40:00
      2010-08-26 02:54:00 -> 2010-08-26 03:00:00
      2010-04-21 06:37:12 -> 2010-04-21 06:40:00
      2010-08-26 02:54:19 -> 2010-08-26 03:00:00
      2010-04-21 06:35:32 -> 2010-04-21 06:40:00
      

      【讨论】:

        【解决方案4】:

        对时间戳进行四舍五入:

        MINUTES = 10.
        
        d = datetime.now()
        t = time.mktime(d.timetuple())
        t = math.ceil((t // 60) / MINUTES) * 600
        d = datetime.fromtimestamp(t)
        

        【讨论】:

          【解决方案5】:
          dt += datetime.timedelta(minutes=9, seconds=59, microseconds=999999)
          dt.replace(minutes=dt.minutes-(dt.minutes%10), seconds=0, microseconds=0)
          

          第一部分加上 9 分钟 59.999999 秒,因此结果总是向上取整。秒部分减去多余的分钟以返回到 10 分钟的边界并将秒设置为零。

          【讨论】:

            猜你喜欢
            • 2017-05-22
            • 1970-01-01
            • 2017-02-11
            • 2011-11-06
            • 1970-01-01
            • 1970-01-01
            • 2011-10-25
            • 2021-12-11
            相关资源
            最近更新 更多