Python中的舍入时间

2024-05-13 22:49:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在控制舍入分辨率的Python中,对与时间相关的类型执行h/m/s舍入操作的优雅、高效和Python方法是什么?

我猜这需要一个时间模运算。示例:

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

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

  • datetime.datetime\datetime.time
  • struct_time

Tags: 方法gt示例类型datetimetime时间分辨率
3条回答

这将把时间数据汇总到问题中提出的分辨率:

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

有关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

使用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

相关问题 更多 >