· python

Python: Difference between two datetimes in milliseconds

I’ve been doing a bit of adhoc measurement of some cypher queries executed via py2neo and wanted to work out how many milliseconds each query was taking end to end.

I thought there’d be an obvious way of doing this but if there is it’s evaded me so far and I ended up calculating the different between two datetime objects which gave me the following timedelta object: ~python >>> import datetime >>> start = datetime.datetime.now() >>> end = datetime.datetime.now() >>> end - start datetime.timedelta(0, 3, 519319) ~

The 3 parts of this object are 'days', 'seconds' and 'microseconds' which I found quite strange!

These are the methods/attributes we have available to us: ~python >>> dir(end - start) ['abs', 'add', 'class', 'delattr', 'div', 'doc', 'eq', 'floordiv', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'mul', 'ne', 'neg', 'new', 'nonzero', 'pos', 'radd', 'rdiv', 'reduce', 'reduce_ex', 'repr', 'rfloordiv', 'rmul', 'rsub', 'setattr', 'sizeof', 'str', 'sub', 'subclasshook', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds'] ~

There’s no 'milliseconds' on there so we’ll have to calculate it from what we do have: ~python >>> diff = end - start >>> elapsed_ms = (diff.days * 86400000) + (diff.seconds * 1000) + (diff.microseconds / 1000) >>> elapsed_ms 3519 ~

Or we could do the following slightly simpler calculation: ~python >>> diff.total_seconds() * 1000 3519.319 ~

And now back to the query profiling!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket