- Calculate Time Difference in Python
- Table of contents
- How to get the time difference between two-time in Python
- Example: Calculate Time Difference in Python
- Get time difference in hours and minutes
- Time Difference between two timestamps in Python
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Python Difference Between Two Dates in Days
- Table of contents
- How to Calculate Difference Between Two Dates in Days
- Example: Days between two dates
- Difference between two date object
- Difference between two datetime object
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
Calculate Time Difference in Python
In this article, you’ll learn how to find the time difference between two-time in Python. For example, we want to measure the execution time of a program. Here, we need to calculate the time difference between the program’s start and end times.
Another example is we may need to capture the time change between the two events. We need to subtract one time/timestamp from another to calculate the time difference between two-time.
After reading this Python article, you’ll learn:
- How to calculate the time interval between the two-time strings.
- get time difference in seconds, minutes, and hours
- Get the time difference between two timestamps in Python
Table of contents
How to get the time difference between two-time in Python
For example, you have a start time and stop time in the format of “10:33:26” ( HH:MM:SS ). The below steps show how to calculate the time difference in hours, minutes, and seconds between two-time in Python.
- Import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
- Convert time strings to a datetime object We have time data in a string format. Before calculating the difference, we need to convert both time strings to a datetime object.
Use the strptime(time_str, format) function to convert a time string into a datetime object as per the corresponding format. The format codes are standard directives for mentioning the string format for parsing. For example, the %H:%M:%S format codes are for hours, minutes, and seconds. - Subtract the end time from the start time 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.
- Get time difference in seconds To get a time difference in seconds, use the timedelta.total_seconds() methods.
- Get time difference in milliseconds Multiply the total seconds by 1000 to get the time difference in milliseconds.
- Get time difference in minutes Divide the seconds by 60 to get the difference in minutes.
- Get time difference in hours Divide the seconds by 3600 to get the final result in hours.
Example: Calculate Time Difference in Python
In this example, we will see how to calculate the seconds and milliseconds between two-time.
from datetime import datetime # start time start_time = "2:13:57" end_time = "11:46:38" # convert time string to datetime t1 = datetime.strptime(start_time, "%H:%M:%S") print('Start time:', t1.time()) t2 = datetime.strptime(end_time, "%H:%M:%S") print('End time:', t2.time()) # get difference delta = t2 - t1 # time difference in seconds print(f"Time difference is seconds") # time difference in milliseconds ms = delta.total_seconds() * 1000 print(f"Time difference is milliseconds")
Start time: 02:13:57 End time: 11:46:38 Time difference is 34361.0 seconds Time difference is 34361000.0 milliseconds
Get time difference in hours and minutes
Note: To calculate the time difference in minutes and hours use the below formulas.
- First, use the above example to get the time difference in seconds between two-time.
- Next, divide the seconds by 60 to get the get time difference in minutes.
- In the end, divide the seconds by 3600 (60*60) to get the time difference in hours.
Example: To get the time difference in hours and minutes between two-time.
from datetime import datetime # start time and end time start_time = datetime.strptime("2:13:57", "%H:%M:%S") end_time = datetime.strptime("11:46:38", "%H:%M:%S") # get difference delta = end_time - start_time sec = delta.total_seconds() print('difference in seconds:', sec) min = sec / 60 print('difference in minutes:', min) # get difference in hours hours = sec / (60 * 60) print('difference in hours:', hours)
difference in seconds: 34361.0 difference in minutes: 572.6833333333333 difference in hours: 9.544722222222223
Time Difference between two timestamps in Python
A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred.
Now, let’s see how to find the difference between the two timestamps in hours, minutes, and seconds.
- First, store the start timestamp in the ‘start’ variable and the end timestamp in the ‘end’ variable.
- Next, use the fromtimestamp() method to convert both start and end timestamps to datetime objects. We convert these timestamps to datetime because we want to subtract one timestamp from another.
- Next, subtract datetime2 from datetime1 to get the difference between two timestamps in the form of timedelta
- Next, use the total_seconds() method to get the difference in seconds.
Example 1: Difference between two timestamps in HH:MM:SS format.
from datetime import datetime # start and end timestamps start_ts = 1652426243.907874 end_ts = 1652436243.907874 # convert timestamps to datetime object dt1 = datetime.fromtimestamp(start_ts) print('Datetime Start:', dt1) dt2 = datetime.fromtimestamp(end_ts) print('Datetime End:', dt2) # Difference between two timestamps # in hours:minutes:seconds format delta = dt2 - dt1 print('Difference is:', delta)
Datetime Start: 2022-05-13 12:47:23.907874 Datetime End: 2022-05-13 15:34:03.907874 Difference is: 2:46:40
The output shows the difference between the two timestamps is 2 hours, 46 minutes, and 40 seconds.
Difference between two timestamps in seconds
Use the below example to get the total seconds between two timestamps.
from datetime import datetime # convert timestamps to datetime object start_ts_ = datetime.fromtimestamp(1652426243.907874) print('Datetime Start:', start_ts_) end_ts = datetime.fromtimestamp(1652436243.907874) print('Datetime End:', end_ts) # Difference between two timestamps in seconds delta = end_ts - start_ts_ print('Difference is seconds:', delta.total_seconds())
Datetime Start: 2022-05-13 12:47:23.907874 Datetime End: 2022-05-13 15:34:03.907874 Difference is seconds: 10000.0
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Python Difference Between Two Dates in Days
After reading this article, you’ll learn how to find the difference between two dates in Python. Also, we’ll see how to calculate the number of days between two dates and datetime objects.
Table of contents
How to Calculate Difference Between Two Dates in Days
Dates can be in any form, such as string, date object, or datetime object. we will see the example of all cases.
Python provides the datetime module to create and manipulate the date and time. The below steps show how to use the datetime module to calculate the difference between two dates in days.
- Import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
- Convert date string to a datetime object There may be a case in which dates are in a string format. Before calculating the difference in days, we need to convert both date strings to a datetime object.
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format .
The format codes are standard directives for mentioning the format of the string for parsing. For example, the %Y/%m/%d format codes are for yyyy-mm-dd - Subtract the date2 from date1 To get the difference between two dates, subtract date2 from date1. A result is a timedelta object. The timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.
- Get a difference in days To get the number of days between two dates, use the timedelta.days attribute
- Get the difference in seconds To get a result in seconds, use the timedelta.seconds attribute
Example: Days between two dates
from datetime import datetime # dates in string format str_d1 = '2021/10/20' str_d2 = '2022/2/20' # convert string to date object d1 = datetime.strptime(str_d1, "%Y/%m/%d") d2 = datetime.strptime(str_d2, "%Y/%m/%d") # difference between dates in timedelta delta = d2 - d1 print(f'Difference is days')
from datetime import datetime as dt res = (dt.strptime('2022/2/20', "%Y/%m/%d") - dt.strptime('2021/10/20', "%Y/%m/%d")).days
Difference between two date object
There are cases in which you receive dates in a date object instead of a string. In such cases, you can directly calculate the difference between them by performing the subtraction operation.
from datetime import date def get_difference(date1, date2): delta = date2 - date1 return delta.days d1 = date(2021, 10, 20) d2 = date(2022, 2, 20) days = get_difference(d1, d2) print(f'Difference is days')
Difference between two datetime object
We need to work with a datetime object instead of a date in some cases. The datetime object contains both date (year-month-day) and time (hours-minutes-seconds) information. Let’s see how to calculate the number of days between two datetime objects.
- First, convert a datetime string to a datetime object using the strptime() function
- Next, calculate the difference by subtracting datetime1 from datetime2 .
from datetime import datetime # datetime in string format str_dt1 = '2021/10/20 09:15:32.36980' str_dt2 = '2022/2/20 04:25:42.120450' # convert string to datetime dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f") dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f") # difference between datetime in timedelta delta = dt2 - dt1 print(f'Difference is days')
The Python timedelta object considers 24 hours as one day, and For calendar days, you’ll need to round down to the nearest day by removing the partial day on both sides. I.e., we need to set hour, minute, and seconds to zero in both datetime.
from datetime import datetime # datetime in string format str_dt1 = '2021/10/20 09:15:32.36980' str_dt2 = '2022/2/20 04:25:42.120450' # convert string to datetime dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f") dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f") rounded_dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0) rounded_dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0) delta = (rounded_dt2 - rounded_dt1) print(delta.days)
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ