pandas 从熊猫日期列中减去当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29901993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:16:12 来源:igfitidea点击:
subtract current time from pandas date column
提问by mark
I have a pandas data frame like
我有一个Pandas数据框,比如
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 myDatecolumn and the current date. How can I do this? I tried the below without much success
我想找出myDate列中的日期与当前日期之间的天数。我怎样才能做到这一点?我尝试了以下但没有多大成功
pd.to_datetime(x['myDate']) - pd.datetime.now().date()
回答by EdChum
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
As does 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
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'], 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

