Python timedelta: microseconds vs milliseconds confusion

Advertisements

I have what appears to be a very silly question.

My impression is that the timedelta.microseconds attribute really returns milliseconds (at least in Python 3.10).

Running the following code:

import sys
from datetime import datetime, timedelta
from time import sleep

print(sys.version)
start: datetime = datetime.now()
sleep(3) # time.sleep takes a non-keyword "secs" argument aka seconds - see docstring
end: datetime = datetime.now()
delta: timedelta = (end - start)
print(delta)
print(delta.microseconds)
print(delta.microseconds / 1000)
print(delta.seconds)

… will print out something in the lines of (my comments at end of line):

3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] # full version info for reference
0:00:03.003650 # representation of the delta as requested
3650 # isn't that >> milliseconds <<<? aka roughly 3 seconds * 1000 ?
3.65 # dividing the delta by 1000 roughly gives me the original argument
3 # accessing the "seconds" attribute instead works as expected --> 3 seconds (roughly)

I couldn’t find anything to clarify this for me in the official 3.10 datetime doc page, which makes me wonder whether this is an actual naming bug or I’m overlooking something obvious.

Note also that the timedelta class doesn’t appear to have a "milliseconds" attribute I can use for comparison.

>Solution :

timedelta stores days, seconds and microseconds. The microseconds you see is the microseconds part of the value, not the seconds converted to microseconds.

Source – https://docs.python.org/3/library/datetime.html#timedelta-objects

Leave a ReplyCancel reply