unclegood
unclegood

Reputation: 289

pandas difference between 2 dates

I am trying to find the day difference between today, and dates in my dataframe.

Below is my conversion of dates in my dataframe

df['Date']=pd.to_datetime(df['Date'])

Below is my code to get today

today1=dt.datetime.today().strftime('%Y-%m-%d')
today1=pd.to_datetime(today1)

Both are converted to pandas.to_datetime, but when I do subtraction, the below error came out.

ValueError: Cannot add integral value to Timestamp without offset.

Can someone help to advise? Thanks!

Upvotes: 1

Views: 3099

Answers (1)

Joe T. Boka
Joe T. Boka

Reputation: 6581

This is a simple example how you can do this:

import pandas
import datetime as dt

First, you have to get today.

today1=dt.datetime.today().strftime('%Y-%m-%d')
today1=pd.to_datetime(today1)

Then, you can construct the data frame:

df = pandas.DataFrame({'Date':'2016-11-24 11:03:10.050000', 'today1': today1 }, index = [0])

In this example I just have 2 columns, each with one value.

Next, you should check the data types:

print(df.dtypes)
Date      datetime64[ns]
today1    datetime64[ns]

If both data types are datetime64[ns], you can then subtract df.Date from df.today1.

print(df.today1 - df.Date)

The output:

0   19 days 12:56:49.950000
dtype: timedelta64[ns]

Upvotes: 1

Related Questions