You can round to anything you want by setting te parameters unit, rnd, and frm. The function below with minimum of import will do the job. T += datetime.timedelta(minutes=(t.minute / lapse + 1) * lapse - t.minute) T += datetime.timedelta(minutes=math.ceil(t.minute / lapse) * lapse - t.minute)Įlif surplus != datetime.timedelta() or lapse < 0: Surplus = datetime.timedelta(seconds=t.second, microseconds=t.microsecond) :param lapse: Lapse to round in minutes (default: 0) :param timestamp: Timestamp to round (default: now) Round a timestamp to a lapse according to specified minutes Other solution: def round_time(timestamp=None, lapse=0): Samples with 1 hour rounding & 15 minutes rounding: print roundTime(datetime.datetime(2012,12,31,23,44,59),datetime.timedelta(hour=1)) Return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond) Rounding = (seconds+roundTo/2) // roundTo * roundTo # // is a floor division, not a comment on following line: Stijn Nevens 2014 - Changed to use only datetime objects as variables """Round a datetime object to a multiple of a timedeltaĪuthor: Thierry Husson 2012 - Use it as you want but don't blame me. Print(round_time(datetime.datetime(2012,12,19,23,00,00),date_delta=datetime.timedelta(hours=1)))įrom the best answer I modified to an adapted version using only datetime objects, this avoids having to do the conversion to seconds and makes the calling code more readable: def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)): Return dt + datetime.timedelta(0, rounding - seconds, - dt.microsecond) Rounding = seconds // round_to * round_to Rounding = (seconds + dt.microsecond/1000000 + round_to) // round_to * round_to # // is a floor division, not a comment on following line (like in javascript): Rounding = (seconds + round_to / 2) // round_to * round_to If seconds % round_to = 0 and dt.microsecond = 0: Round a datetime object to a multiple of a timedeltaĭt : datetime.datetime object, default now.ĭateDelta : timedelta object, we round to a multiple of this, default 1 minute. import datetimeĭef round_time(dt=None, date_delta=datetime.timedelta(minutes=1), to='average'): Tested for date_delta of "X hours" or "X minutes" or "X seconds". Update = comment Bart incorporated thank you. Update = comment Spinxz incorporated thank you. Rounding up, down and rounding to nearest. I used Stijn Nevens code (thank you Stijn) and have a little add-on to share.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |