subtract current time from pandas date column

风流意气都作罢 提交于 2021-02-18 22:12:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!