Python中的时间舍入
在Python中,有没有一种优雅、高效且符合Python风格的方法,可以对时间相关的类型进行小时、分钟、秒的四舍五入操作,并且可以控制四舍五入的精度呢?
我猜这可能需要用到时间的取模运算。下面是一些示例:
- 20:11:13 % (10秒) => (3秒)
- 20:11:13 % (10分钟) => (1分钟和13秒)
我能想到的相关时间类型有:
datetime.datetime
\datetime.time
struct_time
8 个回答
5
这段代码会把时间数据按照问题中要求的精度进行向上取整:
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)
16
可以试试用 datetime.timedelta
这个东西:
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
18
如果你想对日期和时间进行四舍五入,可以看看这个函数:
https://stackoverflow.com/a/10854034/1431079
使用示例:
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00