Python中的舍入时间

Jon*_*han 25 python time datetime rounding modulo

什么是优雅,高效和Pythonic方式在Python中执行时间相关类型的ah/m/s舍入操作,并控制舍入分辨率?

我的猜测是需要时间模运算.说明性示例:

  • 20:11:13%(10秒)=>(3秒)
  • 20:11:13%(10分钟)=>(1分13秒)

我能想到的相关时间相关类型:

  • datetime.datetime\datetime.time
  • struct_time

Le *_*oid 16

对于datetime.datetime舍入,请参阅此函数: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
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 15

如何使用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
Run Code Online (Sandbox Code Playgroud)

  • 这将与`datetime.time`一起使用,但不与`datetime.datetime`一起使用,因为你没有考虑日期 (4认同)

cai*_*ura 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)
Run Code Online (Sandbox Code Playgroud)


Pie*_*rre 2

我想我会以秒为单位转换时间,并从那时起使用标准模运算。

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

72673 % 10 = 3

72673 % (10*60) = 73

这是我能想到的最简单的解决方案。