In pandas, you can calculate the time difference between two dates or times by subtracting them and getting the Timedelta object as a result. The Timedelta object represents the difference between two dates or times in terms of days, seconds, microseconds, milliseconds, minutes, hours, weeks, or years.
For example, consider the following two dates:
import pandas as pd date1 = pd.to_datetime("2022-01-01") date2 = pd.to_datetime("2021-01-01")
You can subtract the two dates to get the time difference:
difference = date1 - date2
The resulting difference will be a Timedelta object representing the difference between the two dates:
Timedelta('365 days 00:00:00')
If you have two columns in a DataFrame with dates or times, you can subtract one from the other to calculate the time difference between the values in each row. For example:
import pandas as pd df = pd.DataFrame({"start_time": [pd.to_datetime("2022-02-15"), pd.to_datetime("2021-01-31")], "end_time": [pd.to_datetime("2022-03-15"), pd.to_datetime("2021-02-28")]}) df["difference"] = df["end_time"] - df["start_time"]
The resulting DataFrame will have an additional column difference with the time difference between the values in the start_time and end_time columns:
start_time end_time difference 0 2022-02-15 2022-03-15 29 days 1 2021-01-31 2021-02-28 28 days