1

I want to get the last 10 minutes in python to be fully divisible by 10.

It shouldn't round to the next 10 minutes, it must be always previous 10 minutes.

For example, output should be as follows:

2019-10-04 20:45:34.903000 -> 2019-10-04 20:40

2019-10-04 20:48:35.403000 -> 2019-10-04 20:40

2019-10-04 20:42:21.903000 -> 2019-10-04 20:40

2019-10-04 20:50:21.204000 -> 2019-10-04 20:50

2019-10-04 20:59:49.602100 -> 2019-10-04 20:50

import datetime

def timeround10(dt):
    #...


print timeround10(datetime.datetime.now())
senjizu
  • 103
  • 12
  • So do you want to modify the datetime object or get a string? Also, have you tried? What do your attempts look like? – Evan Oct 04 '19 at 17:57
  • 1
    Possible duplicate of [How to round the minute of a datetime object python](https://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python) – MyNameIsCaleb Oct 04 '19 at 17:57
  • It is not duplicate. The example in the link you gave rounds to the nearest. For example: 10:46 to 10:50 – senjizu Oct 04 '19 at 18:01

2 Answers2

5

The easiest way is to construct a new datetime with the desired values.

def timeround10(dt):
    return datetime.datetime(dt.year, dt.month, dt.day, dt.hour, (dt.minute // 10) * 10))
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0
def timeround10(dt):
    return dt.replace(second=dt.second // 10, microsecond=0)
Evan
  • 2,120
  • 1
  • 15
  • 20