93

Given the python code below, please help me understand what is happening there.

start_time = time.time()
time.sleep(42)
end_time = time.time()

uptime = end_time - start_time

human_uptime = str(datetime.timedelta(seconds=int(uptime)))

So I get the difference between start time and end time, on line 5 I round up the duration by casting and what now, what's the further explanation?

I know what delta means(average or difference), but why do I have to pass seconds = uptime to timedelta and why does the string casting works so nicely that I get HH:MM:SS ?

Paul
  • 20,883
  • 7
  • 57
  • 74

2 Answers2

117

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

maufcost
  • 169
  • 11
utdemir
  • 26,532
  • 10
  • 62
  • 81
13

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print(datetime.timedelta(seconds=int(uptime)))
Ahmed
  • 2,825
  • 1
  • 25
  • 39
mac
  • 42,153
  • 26
  • 121
  • 131
  • 1
    You hint at this, but It's worth explicitly noting that timedelta does a lot more than display things in HH:MM:SS format. A timedelta object is used whenever you need to take a difference between two datetime objects. – Wilduck Jul 19 '11 at 15:10
  • 1
    It isn't the `__repr__` method, it is `__str__` method. – utdemir Jul 19 '11 at 15:11
  • 1
    Not the `__repr__()` of timedelta, but its `__str__()` method. `print` calls `__str()__` for you. – bgporter Jul 19 '11 at 15:12