Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract current time from pandas date column

Tags:

python

pandas

I have a pandas data frame like

x = pd.DataFrame(['05/06/2015 00:00', '22/06/2015 00:00', None], columns=['myDate'])

I want to find out the number of days between the dates in the myDate column and the current date. How can I do this? I tried the below without much success

pd.to_datetime(x['myDate']) - pd.datetime.now().date()
like image 826
mark Avatar asked Apr 27 '15 17:04

mark


1 Answers

the following works for me:

In [9]:

df = pd.DataFrame(['05/06/2015 00:00', '22/06/2015 00:00', None], columns=['myDate'])
df['myDate']= pd.to_datetime(df['myDate'], errors='coerce')
df
Out[9]:
      myDate
0 2015-05-06
1 2015-06-22
2        NaT
In [10]:

df['diff'] = df['myDate'] - pd.Timestamp.now().normalize()
df
Out[10]:
      myDate    diff
0 2015-05-06  9 days
1 2015-06-22 56 days
2        NaT     NaT

As does your version:

In [13]:

df['diff'] = df['myDate'] - pd.Timestamp.now().normalize()
df
Out[13]:
      myDate    diff
0 2015-05-06  9 days
1 2015-06-22 56 days
2        NaT     NaT

A more compact version:

In [15]:

df = pd.DataFrame(['05/06/2015 00:00', '22/06/2015 00:00', None], columns=['myDate'])
df['diff']= pd.to_datetime(df['myDate'], errors='coerce') - pd.Timestamp.now().normalize()
df
Out[15]:
             myDate    diff
0  05/06/2015 00:00  9 days
1  22/06/2015 00:00 56 days
2              None     NaT
like image 90
EdChum Avatar answered Oct 24 '22 04:10

EdChum