Rounding time in Python

前端 未结 8 1896
清酒与你
清酒与你 2020-12-24 13:34

What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?

相关标签:
8条回答
  • 2020-12-24 14:03

    I use following code snippet to round to the next hour:

    import datetime as dt
    
    tNow  = dt.datetime.now()
    # round to the next full hour
    tNow -= dt.timedelta(minutes = tNow.minute, seconds = tNow.second, microseconds =  tNow.microsecond)
    tNow += dt.timedelta(hours = 1)
    
    0 讨论(0)
  • 2020-12-24 14:08

    I think I'd convert the time in seconds, and use standard modulo operation from that point.

    20:11:13 = 20*3600 + 11*60 + 13 = 72673 seconds

    72673 % 10 = 3

    72673 % (10*60) = 73

    This is the easiest solution I can think about.

    0 讨论(0)
提交回复
热议问题