Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python timedelta: microseconds vs milliseconds confusion

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading