问题
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()
回答1:
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
来源:https://stackoverflow.com/questions/29901993/subtract-current-time-from-pandas-date-column