How to round up (always) time to nearest ten?
I did not want to take a risk of coming up with a hack for this because it involves datetime
objects. Basically, I want to do the conversion as follows:
2010-04-21 开发者_如何学C06:37:53 -> 2010-04-21 06:40:00
2010-08-26 02:54:00 -> 2010-08-26 03:00:00
2010-04-21 06:37:12 -> 2010-04-21 06:40:00
2010-08-26 11:54:19 -> 2010-08-27 00:00:00
Is there a built-in way of doing this?
You would need to convert your time into a unix timestamp and round the timestamp as wished.
round(Timestamp / 60 seconds [minutes conversion] / 10 [round precision]) * 60 * 10 [to get the timestamp back]
You want to round-off only minutes. You'll get the correct answer even if you ignore the seconds and microseconds.
In that case this is one liner:
def round_minutes(t): # t is a datetime object
return t - datetime.timedelta( minutes = t.minute - round(t.minute, -1), seconds = t.second, microseconds = t.microsecond)
You take the timedelta of time between original minute and rounded off minute to nearest 10 and apply that difference. Also, to zerofy seconds and microseconds, you add them in the delta as well.
This seems to be working for me.
def round_up(tm):
upmins = math.ceil(float(tm.minute)/10)*10
diffmins = upmins - tm.minute
newtime = tm + datetime.timedelta(minutes=diffmins)
newtime = newtime.replace(second=0)
return newtime
Conversions:
2010-04-21 06:37:53 -> 2010-04-21 06:40:00
2010-08-26 02:54:00 -> 2010-08-26 03:00:00
2010-04-21 06:37:12 -> 2010-04-21 06:40:00
2010-08-26 02:54:19 -> 2010-08-26 03:00:00
2010-04-21 06:35:32 -> 2010-04-21 06:40:00
Rounding on the timestamp works:
MINUTES = 10.
d = datetime.now()
t = time.mktime(d.timetuple())
t = math.ceil((t // 60) / MINUTES) * 600
d = datetime.fromtimestamp(t)
dt += datetime.timedelta(minutes=9, seconds=59, microseconds=999999)
dt.replace(minutes=dt.minutes-(dt.minutes%10), seconds=0, microseconds=0)
The first part adds 9 minutes, 59.999999 seconds so that the result is always rounded up. The seconds part subtracts the excess minutes to get back to a 10-minute boundary and sets the seconds to zero.
精彩评论