user29337 user29337 - 1 year ago 94
Python Question

datetime arithmetic with microsecond resolution in Python

I want to calculate the difference (in terms of days, hour, min, sec, microsecond) between two time stamps (having microsecond resolution) in python e.g. between (1)

2016-05-10 11:32:18.025635
and (2)
2016-05-13 18:59:52.094672

Any pointers, how to do it?

Answer Source

You can use the python-dateutil package:

>>> import dateutil.parser
>>> d1 = dateutil.parser.parse('2016-05-10 11:32:18.025635')
>>> d2 = dateutil.parser.parse('2016-05-13 18:59:52.094672')
>>> d2 - d1
datetime.timedelta(3, 26854, 69037)

This will give you a datetime.timedelta object which represents the time difference between the two datetime objects.

If you don't want to install a package then it can also be done using datetime.strptime but in that case you have to define what the string looks like.