1

I'm trying to get difference between two datetimes, but I don't know why I'm getting 0 when trying to get microseconds:

from dateutil.parser import parse

x = parse("2019-03-25T17:33:08.829-03:00")
y = parse("2019-03-25T18:07:08.829-03:00")

result = y - x
print(result.microseconds) // prints 0

Tried: Python - time difference in milliseconds not working for me and Python speed testing - Time Difference - milliseconds

with no luck.

What I'm doing wrong here?

guijob
  • 4,413
  • 3
  • 20
  • 39

2 Answers2

5

One of the answers of the posts you linked says:

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

If you want the microseconds portion, what else did you expect? The fractional part of the seconds of both your dates are equal, so the difference is 0.

Otherwise, use result.total_seconds() * 1e6 + result.microseconds.

Jona
  • 1,218
  • 1
  • 10
  • 20
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
2

You did not compute the difference in microseconds. Rather, you found the time difference of 34 minutes, and asked for the microseconds component of that difference. The time difference is 0:34:00. Of this figure, every component except minutes is 0.

To see this effect, insert this simple tracing code into your program:

print(result, type(result))
print(x, type(x))
print(y, type(y))

Output:

2019-03-25 17:33:08.829000-03:00 <class 'datetime.datetime'>
2019-03-25 18:07:08.829000-03:00 <class 'datetime.datetime'>
0:34:00 <class 'datetime.timedelta'>

You need to take the entire timedelta and convert it to microseconds. Now that you see the problem, I'll bet you can fix it on your own. :-)

Prune
  • 76,765
  • 14
  • 60
  • 81