Subtract current time from pandas date column

I have a pandas dataframe like

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

      

I want to know the number of days between the dates in the column myDate

and the current date. How can i do this? I have tried below without much success

pd.to_datetime(x['myDate']) - pd.datetime.now().date()

      

+3


source to share


1 answer


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'], coerce=True)
df
Out[9]:
      myDate
0 2015-05-06
1 2015-06-22
2        NaT
In [10]:

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

      

Like your version:



In [13]:

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

      

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'], coerce=True) - pd.datetime.now().date()
df
Out[15]:
             myDate    diff
0  05/06/2015 00:00  9 days
1  22/06/2015 00:00 56 days
2              None     NaT

      

+6


source







All Articles