Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding time in Python

What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?

My guess is that it would require a time modulo operation. Illustrative examples:

  • 20:11:13 % (10 seconds) => (3 seconds)
  • 20:11:13 % (10 minutes) => (1 minutes and 13 seconds)

Relevant time related types I can think of:

  • datetime.datetime \ datetime.time
  • struct_time
like image 665
Jonathan Livni Avatar asked Jul 24 '11 11:07

Jonathan Livni


People also ask

How do I remove seconds from a time in Python?

If you just want strings, you could remove the trailing seconds with a regex ':\d\d$' .

How do you find the nearest integer in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.


1 Answers

For a datetime.datetime rounding, see this function: https://stackoverflow.com/a/10854034/1431079

Sample of use:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60) 2013-01-01 00:00:00 
like image 87
Le Droid Avatar answered Sep 28 '22 16:09

Le Droid