Rounding time in Python

2019-02-01 19:48发布

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?

My guess is that it would require a time modulo operation. Illustrative examples:

  • 20:11:13 % (10 seconds) => (3 seconds)
  • 20:11:13 % (10 minutes) => (1 minutes and 13 seconds)

Relevant time related types I can think of:

  • datetime.datetime \ datetime.time
  • struct_time

8条回答
贪生不怕死
2楼-- · 2019-02-01 20:29

You can convert both times to seconds, do the modulo operati

from datetime import time

def time2seconds(t):
    return t.hour*60*60+t.minute*60+t.second

def seconds2time(t):
    n, seconds = divmod(t, 60)
    hours, minutes = divmod(n, 60)
    return time(hours, minutes, seconds)

def timemod(a, k):
    a = time2seconds(a)
    k = time2seconds(k)
    res = a % k
    return seconds2time(res)

print(timemod(time(20, 11, 13), time(0,0,10)))
print(timemod(time(20, 11, 13), time(0,10,0)))

Outputs:

00:00:03
00:01:13
查看更多
\"骚年 ilove
3楼-- · 2019-02-01 20:32

How about use datetime.timedeltas:

import time
import datetime as dt

hms=dt.timedelta(hours=20,minutes=11,seconds=13)

resolution=dt.timedelta(seconds=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:00:03

resolution=dt.timedelta(minutes=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:01:13
查看更多
登录 后发表回答