Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round the minute of a datetime object

I have a datetime object produced using strptime().

>>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) 

What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it.

min = round(tm.minute, -1) 

However, as with the above example, it gives an invalid time when the minute value is greater than 56. i.e.: 3:60

What is a better way to do this? Does datetime support this?

like image 386
Lucas Manco Avatar asked Aug 12 '10 00:08

Lucas Manco


People also ask

How can I get minutes from datetime?

To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do you round date and time?

Rounding Up Date ObjectsRound up to the next closest rounding unit boundary. For example, if the rounding unit is month then next closest boundary of 2000-01-01 is 2000-02-01 00:00:00 .


1 Answers

This will get the 'floor' of a datetime object stored in tm rounded to the 10 minute mark before tm.

tm = tm - datetime.timedelta(minutes=tm.minute % 10,                              seconds=tm.second,                              microseconds=tm.microsecond) 

If you want classic rounding to the nearest 10 minute mark, do this:

discard = datetime.timedelta(minutes=tm.minute % 10,                              seconds=tm.second,                              microseconds=tm.microsecond) tm -= discard if discard >= datetime.timedelta(minutes=5):     tm += datetime.timedelta(minutes=10) 

or this:

tm += datetime.timedelta(minutes=5) tm -= datetime.timedelta(minutes=tm.minute % 10,                          seconds=tm.second,                          microseconds=tm.microsecond) 
like image 98
Omnifarious Avatar answered Sep 21 '22 15:09

Omnifarious