Pandas How To Uncategorized How to subtract dates in Pandas?

How to subtract dates in Pandas?

In Pandas, you can subtract two dates to get the time delta between them. The result will be a Timedelta object, which 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 delta:

delta = date1 - date2

The resulting delta will be a Timedelta object representing the difference between the two dates:

Timedelta('365 days 00:00:00')

You can also subtract a date from a Series of dates, or subtract a date from a date stored in a DataFrame column, and the result will be a Series of Timedelta objects.

Leave a Reply

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

Related Post