Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the microseconds from a timedelta object?

I do a calculation of average time, and I would like to display the resulted average without microseconds.

avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes) 
like image 486
Hobbestigrou Avatar asked Aug 27 '13 16:08

Hobbestigrou


People also ask

How do you get milliseconds from Timedelta?

Use the timedelta() class from the datetime module to add milliseconds to datetime, e.g. result = dt + timedelta(milliseconds=300) . The timedelta class can be passed a milliseconds argument and adds the specified number of milliseconds to the datetime.

How do you round Timedelta?

To round the Timedelta with specified resolution, use the timestamp. round() method.


2 Answers

If it is just for the display, this idea works :

avgString = str(avg).split(".")[0] 

The idea is to take only what is before the point. It will return 01:23:45 for 01:23:45.1235

like image 193
sangorys Avatar answered Sep 22 '22 15:09

sangorys


Take the timedelta and remove its own microseconds, as microseconds and read-only attribute:

avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes) avg = avg - datetime.timedelta(microseconds=avg.microseconds) 

You can make your own little function if it is a recurring need:

import datetime  def chop_microseconds(delta):     return delta - datetime.timedelta(microseconds=delta.microseconds) 

I have not found a better solution.

like image 23
Hobbestigrou Avatar answered Sep 22 '22 15:09

Hobbestigrou