The Wayback Machine - https://web.archive.org/web/20240603222730/https://www.geeksforgeeks.org/calculate-time-difference-in-python/
Open In App

Calculate Time Difference in Python

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to find the gap between two times in Python.

If we want to know the difference at which some particular events has occurred then we should know the time gap between them.

Example:

Input: Start time is : 06:20:50, End time is : 11:56:18
Output: Time difference in seconds is 20128.0 seconds 
Explanation: The time difference between the two times is 20128 seconds.

We will discuss the following topics:

  • Calculate the time difference in hours, minutes and seconds
  • Calculate the time interval between two given times
  • Using the divmod( ) function

Calculate the time difference in hours, minutes and seconds

For finding differences in hours, minutes and seconds we will perform the following actions:

  • We will import daytime from daytime module
  • We will have start and end time of event
  • Then calculate the difference between them
  • And finally calculate the difference in hours, minutes and seconds

Python3




from datetime import datetime
  
start = datetime.strptime("4:25:40", "%H:%M:%S")
end = datetime.strptime("11:40:10", "%H:%M:%S")
  
difference = end - start
  
seconds = difference.total_seconds()
print('difference in seconds is:', seconds)
  
minutes = seconds / 60
print('difference in minutes is:', minutes)
  
hours = seconds / (60 * 60)
print('difference in hours is:', hours)


 Output:

difference in seconds is: 26070.0
difference in minutes is: 434.5
difference in hours is: 7.241666666666666

Calculate the time interval between two given times

Now we will calculate the time difference in seconds between two given times.

We will perform the following actions:

  • Import daytime from daytime module
  • We will have a start time and end time
  • Calculate the difference
  • Finally, calculate the difference in seconds

Python3




from datetime import datetime
  
start = "2:13:57"
end = "11:46:38"
  
  
time1 = datetime.strptime("6:20:50", "%H:%M:%S")
print('Start time is :', time1.time())
  
time2 = datetime.strptime("11:56:18", "%H:%M:%S")
print('End time is :', time2.time())
  
  
delta = time2 - time1
  
  
print("Time difference in seconds is", delta.total_seconds(), "seconds")


Output:

Start time is : 06:20:50
End time is : 11:56:18
Time difference in seconds is 20128.0 seconds

Using the divmod( ) function

We can get a more precise time difference using the divmod( ) function. Using this function get the difference in a number of days also.

Python3




import datetime
    
time1 = datetime.datetime(2018, 10, 12, 20, 15, 40)
time2 = datetime.datetime(2015, 2, 10, 15, 41, 30)
  
difference = time1 - time2 
print('Difference is : ', difference)
    
minutes = divmod(difference.total_seconds(), 60) 
print('Difference in minutes: ', minutes[0],
      'minutes', minutes[1], 'seconds')
    
  
minutes = divmod(difference.seconds, 60) 
print('Total difference in minutes: ', minutes[0], 'minutes',minutes[1], 'seconds')


Output:

Difference is :  1340 days, 4:34:10
Difference in minutes:  1929874.0 minutes 10.0 seconds
Total difference in minutes:  274 minutes 10 seconds

Finding the execution time of a program

Now we will discuss how we can find the total time taken by the program to be executed.

Python3




from datetime import datetime
  
start_time = datetime.now()
  
for i in range(10000):
    i**100
  
end_time = datetime.now()
  
time_difference = (end_time - start_time).total_seconds() * 10**3
print("Execution time of program is: ", time_difference, "ms")


Output:

Execution time of program is:  24.488 ms


Similar Reads

Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Python program to find difference between current time and given time
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format. Examples: Input : h1=7, m1=20, h2=9, m2=45 Output : 2 : 25 The current time is 7 : 20 and given
2 min read
Python program to calculate acceleration, final velocity, initial velocity and time
Here we can find the acceleration (a), final velocity(v), initial velocity(u) and time(t) using the formula a = (v-u)/t. At first, functions are defined for all four types of calculations, in which they will accept three inputs and assign the value in three different variables. Then the fourth value is calculated using the acceleration formula and
2 min read
Program to calculate the Round Trip Time (RTT)
Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgment of that signal to be received. This time, therefore, consists of the propagation times between the two-point of the signal. On the Internet, an end-user can determine the RTT to and from an IP(Internet Protocol) address
2 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Python | time.time() method
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. Note: The epoch is the point where the time starts, and is platform dependent. On Windows and
2 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
Convert Epoch Time to Date Time in Python
Epoch time, also known as Unix time or POSIX time, is a way of representing time as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Converting epoch time to a human-readable date and time is a common task in programming, especially in Python. In this article, we will explore some si
3 min read
Python | Calculate difference between adjacent elements in given list
Given a list, the task is to create a new list containing difference of adjacent elements in the given list. Method #1: Using zip() C/C++ Code # Python code to demonstrate # to calculate difference # between adjacent elements in list # initialising _list ini_list = [5, 4, 89, 12, 32, 45] # printing iniial_list print("intial_list",
3 min read
Practice Tags :