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条回答
Lonely孤独者°
2楼-- · 2019-02-01 20:15

For a datetime.datetime rounding, see this function: https://stackoverflow.com/a/10854034/1431079

Sample of use:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00
查看更多
神经病院院长
3楼-- · 2019-02-01 20:15
def round_dt_to_seconds(dt):
    datetime.timedelta(seconds=dt.seconds)
查看更多
Anthone
4楼-- · 2019-02-01 20:17

This will round up time data to a resolution as asked in the question:

import datetime as dt
current = dt.datetime.now()
current_td = dt.timedelta(hours=current.hour, minutes=current.minute, seconds=current.second, microseconds=current.microsecond)

# to seconds resolution
to_sec = dt.timedelta(seconds=round(current_td.total_seconds()))
print dt.datetime.combine(current,dt.time(0))+to_sec

# to minute resolution
to_min = dt.timedelta(minutes=round(current_td.total_seconds()/60))
print dt.datetime.combine(current,dt.time(0))+to_min

# to hour resolution
to_hour = dt.timedelta(hours=round(current_td.total_seconds()/3600))
print dt.datetime.combine(current,dt.time(0))+to_hour
查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-01 20:17

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.

查看更多
够拽才男人
6楼-- · 2019-02-01 20:24

Here is a lossy* version of hourly rounding:

dt = datetime.datetime
now = dt.utcnow()
rounded = dt.utcfromtimestamp(round(now.timestamp() / 3600, 0) * 3600)

Same principle can be applied to different time spans.

*The above method assumes UTC is used, as any timezone information will be destroyed in conversion to timestamp.

查看更多
Evening l夕情丶
7楼-- · 2019-02-01 20:25

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)
查看更多
登录 后发表回答