Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract datetimes / timestamps in python

Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:

2015-08-10 19:33:27.653
2015-08-10 19:31:28.209

How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.

like image 431
Jeff F Avatar asked Aug 10 '15 21:08

Jeff F


People also ask

Can you subtract Datetimes in python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How do you find the difference between two timestamps in python?

To get the difference between two-time, subtract time1 from time2. A result is a timedelta object. The timedelta represents a duration which is the difference between two-time to the microsecond resolution. To get a time difference in seconds, use the timedelta.

How do you subtract two date strings in python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.


2 Answers

Parse your strings as datetime.datetime objects and subtract them:

from datetime import datetime

d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")

print(d1 - d2)

Gives me:

0:01:59.444000

Also check out timedelta documentation for all possible operations.

like image 109
Yaroslav Admin Avatar answered Sep 19 '22 12:09

Yaroslav Admin


you can do subtraction on 2 datetime objects to get the difference

>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10

convert your strings to datetime objects with time.strptime

datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
like image 26
Chris Montanaro Avatar answered Sep 17 '22 12:09

Chris Montanaro