Calculate Time Difference in Milliseconds Between Two datetimes in Python (Example)


In this Python tutorial, you’ll learn how to return the time difference between two datetimes in milliseconds.

The post is structured as follows:

Let’s dig in.


Example Data

For the examples of this tutorial, we’ll also have to import the datetime module:

import datetime                                                 # Import datetime module

Now, we create two example datetimes, consider the two code boxes below:

my_date_1 = datetime.datetime(2022, 5, 24, 11, 20, 12, 987123)  # 1st example datetime object
# 2022-05-24 11:20:12.987123
my_date_2 = datetime.datetime(2022, 6, 16, 13, 30, 27, 189553)  # 2nd example datetime object
# 2022-06-16 13:30:27.189553

Let’s compute these two datetime objects and find out the time difference…


Example: Show the Time Difference in Milliseconds

To get the time difference of two datetime objects, we simply subtract them from each other:

my_diff_default = my_date_2 - my_date_1                         # Get default time difference
# 23 days, 2:10:14.202430

As you can see on the output above, the default timedelta is not in milliseconds.

To receive the time difference in milliseconds, we have to do a little workaround by applying the total_seconds function, which transforms the time difference into seconds, followed by a multiplication with factor 1000:

my_diff_milli_sec = my_diff_default.total_seconds() * 1000      # Return difference in milliseconds 
# 1995014202.43

That’s it, the time difference between our two datetimes is: 1995014202.43 milliseconds.


Video & Further Resources

I have recently released a video on the Statistics Globe YouTube channel, which shows the Python programming syntax of this article. Please find the video below.



Furthermore, you might want to have a look at the other tutorials on this website.


Summary: In this Python tutorial, you have learned how to print the difference between two datetimes in milliseconds. If you have any additional questions, please let me know in the comments. Furthermore, don’t forget to subscribe to my email newsletter for updates on the newest tutorials.


Matthias Bäuerlen Python Programmer

This page was created in collaboration with Matthias Bäuerlen. Have a look at Matthias’ author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.