Understanding timedelta

前端 未结 2 454
名媛妹妹
名媛妹妹 2020-12-04 12:13

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_         


        
2条回答
  •  情话喂你
    2020-12-04 12:35

    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

提交回复
热议问题