senjizu
senjizu

Reputation: 103

How to round datetime previous 10 minute with python

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())

Upvotes: 1

Views: 678

Answers (2)

Evan
Evan

Reputation: 2301

def timeround10(dt):
    return dt.replace(second=dt.second // 10, microsecond=0)

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308111

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))

Upvotes: 5

Related Questions