我有一列花车。我想将它们转换为格式为hh:mm
的时间戳。我也希望将它们四舍五入到最近的半小时。
这是转换规则:
1.0
表示00:01
,我想将它们四舍五入到00:00
735.0
表示07:35
,我想将它们四舍五入到07:30
2346.0
表示23:46
,我想将它们四舍五入到00:00
答案 0 :(得分:1)
试试这个(没有经过全面测试,但你明白了):
from datetime import date, timedelta, datetime, time
def roundTime(dt=None, dateDelta=timedelta(minutes=15)):
"""Round a datetime object to a multiple of a timedelta
dt : datetime.datetime object, default now.
dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
Stijn Nevens 2014 - Changed to use only datetime objects as variables
"""
roundTo = dateDelta.total_seconds()
if dt == None : dt = datetime.now()
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
time_input = 735.0
dt = datetime.strptime(str(int(time_input)).zfill(4), "%H%M")
print(roundTime(dt,timedelta(minutes=15)).strftime('%H:%M'))
round_time func来自
How to round the minute of a datetime object python
干杯