How do I find the time difference between two datetime objects in python?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
Subtracting the later time from the first time difference = later_time - first_time
creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
Python - Calculate the difference between two datetime.time objects
To calculate the difference, you have to convert the datetime.time
object to a datetime.datetime
object. Then when you subtract, you get a timedelta
object. In order to find out how many hours the timedelta
object is, you have to find the total seconds and divide it by 3600
.
# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600
Find time difference between two dates in python
import datetime
dt_str_a = '2020-06-29 16:15:27'
dt_str_b = '2020-07-12 12:00:00'
dt_a = datetime.datetime.strptime(dt_str_a, '%Y-%m-%d %H:%M:%S')
dt_b = datetime.datetime.strptime(dt_str_b, '%Y-%m-%d %H:%M:%S')
print(dt_b - dt_a)
print((dt_b - dt_a).days)
->
12 days, 19:44:33 # <---- precise value
12 # <---- number of days only
How do I check the difference, in seconds, between two dates?
if you want to compute differences between two known dates, use total_seconds
like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0
#note that seconds doesn't give you what you want:
(b-a).seconds
0
Time difference in python using datetime
This is a manual solution, I suppose that through libraries it can be obtained. You can use the absolute value to avoid negatives
import datetime
now = datetime.datetime.now()
current_time = str(now.hour) +':'+ str(now.minute) +':'+ str(now.second)
another_time = '06:05:00'
splitted_current_time=[int(x) for x in current_time.split(":")]
splitted_another_time=[int(x) for x in another_time.split(":")]
diference=[];
for i in range(0,3):
diference.append(splitted_current_time[i]-splitted_another_time[i])
print(str(diference[0])+':'+str(diference[1])+':'+str(diference[2]))
How do you get the difference between two time objects in Python
The class datetime.time
does not support object subtraction for the same reason it doesn't support object comparison, i.e. because its objects might not define their tzinfo
attribute:
comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.
You should use datetime.datetime
which include both the date and the time.
If the two times refers to a single day, you can tell python that the date is today, with date.today()
and combine the date with the time using datetime.combine
.
Now that you have datetimes you can perform subtraction, this will return a datetime.timedelta instance, which the method total_seconds()
that will return the number of seconds (it's a float
that includes the microseconds information). So multiply by 106 and you get the microseconds.
from datetime import datetime, date, time
x = time(9, 30, 30, 0)
y = time(9, 30, 31, 100000)
diff = datetime.combine(date.today(), y) - datetime.combine(date.today(), x)
print diff.total_seconds() * (10 ** 6) # 1100000.0
You can also just use timedeltas:
from datetime import timedelta
x = timedelta(hours=9, minutes=30, seconds=30)
y = timedelta(hours=9, minutes=30, seconds=31, microseconds=100000)
print (y - x).total_seconds() * (10 ** 6) # 1100000.0
How to calculate the time interval between two time strings
Yes, definitely datetime
is what you need here. Specifically, the datetime.strptime()
method, which parses a string into a datetime
object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta
object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime
.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00
and s2 = 05:00:00
. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
(of course you need to include from datetime import timedelta
somewhere). Thanks to J.F. Sebastian for pointing out this use case.
How do I find the difference in milliseconds between two datetime objects in Python?
This is how you can compute the different between two time
objects. It is a hack which involves adding the same date to both objects.
By construction it assumes both times relate to the same day.
from datetime import datetime, date, time
obs_data = {'RA': "22:24:05.52" }
pred_data = {'RA':"22:24:05.60"}
RA_1 = datetime.strptime(obs_data['RA'], '%H:%M:%S.%f').time()
RA_2 = datetime.strptime(pred_data['RA'], '%H:%M:%S.%f').time()
diff = datetime.combine(date.today(), RA_2) - datetime.combine(date.today(), RA_1)
diff.total_seconds() * (10 ** 3)
# 80.0 [ms]
Related Topics
Importing a CSV File into a SQLite3 Database Table Using Python
Drf: Simple Foreign Key Assignment with Nested Serializers
Find All Occurrences of a Key in Nested Dictionaries and Lists
Tkinter.Tclerror: Image "Pyimage3" Doesn't Exist
How to Find the Mime Type of a File in Python
Accessing Elements of Python Dictionary by Index
Getting a Hidden Password Input
Using Pandas to Pd.Read_Excel() for Multiple Worksheets of the Same Workbook
How to Explode a List Inside a Dataframe Cell into Separate Rows
Order' of Unordered Python Sets
How Exactly Does a Generator Comprehension Work
What Does "Hashable" Mean in Python
How Are Tuples Unpacked in for Loops
How to Get Multiline Input from the User
How to Pass Another Entire Column as Argument to Pandas Fillna()