Remove the microseconds from a timedelta object
Asked Answered
W

8

71

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

avg = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)
Woolley answered 27/8, 2013 at 16:12 Comment(3)
What is 'datetimes'... a list of timedeltas? If so, the sum returns a timedelta object including microseconds... so what's the problem?Addam
avg.strftime("%Y-%m-%d %H:%M:%S"), but it will return string.Parliamentary
@Addam I changed the name of the variable from datetimes to timedeltas, as I agree that it is meant to be a list of timedeltasCharity
W
66

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

avg = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)
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.

Woolley answered 27/8, 2013 at 16:12 Comment(0)
W
70

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

Wargo answered 16/4, 2015 at 8:33 Comment(1)
this one is stupid simple and awesome. should be considered the best answer imhoFactor
W
66

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

avg = sum(timedeltas, datetime.timedelta(0)) / len(timedeltas)
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.

Woolley answered 27/8, 2013 at 16:12 Comment(0)
C
20

another option, given timedelta you can do:

avg = datetime.timedelta(seconds=math.ceil(avg.total_seconds()))

You can replace the math.ceil(), with math.round() or math.floor(), depending on the situation.

Corrosion answered 28/3, 2017 at 7:38 Comment(0)
A
9
c -= timedelta(microseconds=c.microseconds)
Agateware answered 14/7, 2021 at 16:3 Comment(0)
T
1

Given that timedelta only stores days, seconds and microseconds internally, you can construct a new timedelta without microseconds:

from datetime import timedelta
timedeltas = [
    timedelta(hours=1, minutes=5, seconds=30, microseconds=9999), 
    timedelta(minutes=35, seconds=17, microseconds=55), 
    timedelta(hours=2, minutes=17, seconds=3, microseconds=1234),
]
avg = sum(timedeltas, timedelta(0)) / len(timedeltas) # timedelta(0, 4756, 670429)
avg = timedelta(days=avg.days, seconds=avg.seconds) # timedelta(0, 4756)
Tweeddale answered 28/3, 2020 at 18:10 Comment(1)
I don't know why this is downvoted, creating a new timedelta with the days and seconds explicitly from the old is not more or less hackish than subtracting the microseconds using another newly created timedelta. This is what I would do at least.Sandbank
C
0

I think this is the best way to get the last minutes without microseconds:

import time
import datetime
NOW = datetime.datetime.now()
LASTMINUTE =  NOW - datetime.timedelta(minutes=1, seconds = NOW.second, microseconds = NOW.microsecond)
Claxton answered 11/9, 2021 at 17:14 Comment(0)
L
0

The answer by Hobbestigrou is okay but it doesn't round. If you want one that leverages pandas.Timedelta.round, here it is:

import datetime
import pandas as pd

td = datetime.timedelta(hours=1, minutes=23, seconds=45, microseconds=678901)
print(td, repr(td))
1:23:45.678901 datetime.timedelta(seconds=5025, microseconds=678901)

td2 = pd.Timedelta(td).round('s').to_pytimedelta()
print(td2, repr(td2))
1:23:46 datetime.timedelta(seconds=5026)

Similarly, if you would prefer to floor instead, there is pandas.Timedelta.floor.

Larghetto answered 11/3 at 18:39 Comment(0)
W
-1

I found this to work for me:

start_time = datetime.now()
some_work()
end time = datetime.now()
print str(end_time - start_time)[:-3]

Output:

0:00:01.955

I thought about this after searching in https://docs.python.org/3.2/library/datetime.html#timedelta-objects

Walliw answered 27/3, 2019 at 14:21 Comment(1)
As mentioned in countless other threads here on stackoverflow, this is not a good idea, as (1) not all timedelta objects are displayed with 6 characters (see the 0 time delta) for the microssecond part and (2) this does not deal with any form of rounding.Cutshall

© 2022 - 2024 — McMap. All rights reserved.