I need to write a function that can ROUND DOWN time to 5 minutes. I mean if it's 17:01 it goes to 17:00, if it's 16:59 it goes to 16:55, if it's 16:51 it goes to 16:50, etc.
Asked
Active
Viewed 535 times
2
-
2What type of variable is the time stored in? – Martin Nov 15 '20 at 14:14
-
2It would be helpful if you post your code as well. – lkdhruw Nov 15 '20 at 14:18
-
2Does this answer your question? [Round down datetime to previous hour](https://stackoverflow.com/questions/41595754/round-down-datetime-to-previous-hour) – FObersteiner Nov 15 '20 at 15:03
3 Answers
1
If you store your time as a string, i.e hh:mm
, the problem becomes very simple.
We only need to change the last character.
Implementation:
def convertStr(s):
x = s[-1]
if(int(x)<5):
return s[:-1] + '0'
else:
return s[:-1] + '5'
Note that we always need 2 characters in hh and mm for this to work

pigeon_the_programmer
- 131
- 6
1
The question I linked in the comments, applied to your question could look like
from datetime import datetime
l = [datetime.strptime('16:59', "%H:%M").time(), datetime.strptime('17:01', "%H:%M").time()]
# [datetime.time(16, 59), datetime.time(17, 1)]
l_rounded = [d.replace(minute=d.minute-d.minute%5) for d in l]
# [datetime.time(16, 55), datetime.time(17, 0)]

Asclepius
- 57,944
- 17
- 167
- 143

FObersteiner
- 22,500
- 8
- 42
- 72
0
If having a datetime.datetime
object, this can be often be done using pandas.Timestamp.floor
.
> import datetime
> import pandas as pd
> dt = datetime.datetime.now()
> dt
datetime.datetime(2022, 9, 6, 12, 43, 17, 640963)
> dt_floored = pd.Timestamp(dt).floor('5T').to_pydatetime()
> dt_floored
datetime.datetime(2022, 9, 6, 12, 40)
I noticed that this doesn't work for some timezones, e.g. America/New_York
.

Asclepius
- 57,944
- 17
- 167
- 143