Title: Calculate Difference Between Dates And Times
Slug: calculate_difference_between_dates_and_times
Summary: How to calculate differences between dates and times for machine learning in Python.
Date: 2017-09-11 12:00
Category: Machine Learning
Tags: Preprocessing Dates And Times
Authors: Chris Albon

Preliminaries


In [1]:
# Load library
import pandas as pd

Create Date And Time Data


In [2]:
# Create data frame
df = pd.DataFrame()

# Create two datetime features
df['Arrived'] = [pd.Timestamp('01-01-2017'), pd.Timestamp('01-04-2017')]
df['Left'] = [pd.Timestamp('01-01-2017'), pd.Timestamp('01-06-2017')]

Calculate Difference (Method 1)


In [3]:
# Calculate duration between features
df['Left'] - df['Arrived']


Out[3]:
date year month day hour minute
0 2001-01-07 2001 1 7 0 0
1 2001-01-14 2001 1 14 0 0
2 2001-01-21 2001 1 21 0 0

Calculate Difference (Method 2)


In [ ]:
# Calculate duration between features
pd.Series(delta.days for delta in (df['Left'] - df['Arrived']))