简体   繁体   English

将时间量取整到最接近的15分钟

[英]Rounding a timedelta to the nearest 15 minutes

I have a timedelta which I would like to round to the nearest 15 minutes. 我有一个timedelta,我想四舍五入到最近的15分钟。 For example, 8h 40m would round up to 8h 45m and 8h 50m would round down to 8h 45m. 例如,8h 40m将舍入为8h 45m,而8h 50m将舍入为8h 45m。

What would be the best way to achieve this? 实现这一目标的最佳方法是什么?

I ended up creating my own solution as I didn't find another way 由于找不到其他方式,我最终创建了自己的解决方案

def round_timedelta(td, period):
    """
    Rounds the given timedelta by the given timedelta period
    :param td: `timedelta` to round
    :param period: `timedelta` period to round by.
    """
    period_seconds = period.total_seconds()
    half_period_seconds = period_seconds / 2
    remainder = td.total_seconds() % period_seconds
    if remainder >= half_period_seconds:
        return timedelta(seconds=td.total_seconds() + (period_seconds - remainder))
    else:
        return timedelta(seconds=td.total_seconds() - remainder)

Used in iPython: 在iPython中使用:

In [4]: print round_timedelta(timedelta(hours=1, minutes=27), timedelta(minutes=15))
1:30:00

In [5]: print round_timedelta(timedelta(hours=1, minutes=30), timedelta(minutes=15))
1:30:00

In [6]: print round_timedelta(timedelta(hours=1, minutes=31), timedelta(minutes=15))
1:30:00

In [7]: print round_timedelta(timedelta(hours=1, minutes=37), timedelta(minutes=15))
1:30:00

In [8]: print round_timedelta(timedelta(hours=1, minutes=38), timedelta(minutes=15))
1:45:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM