如何从 pandas 日期时间中删除日期、小时和秒,以便只剩下分钟?我有一个日期表,格式如下:
Date
2015-04-18 23:33:58
2015-04-19 14:32:08
2015-04-20 18:42:44
2015-04-20 21:41:19
我想要:
Date
33
32
42
41
我尝试使用的代码是:
fiveMin['Date'] = fiveMin['Date'] - pd.Timedelta(fiveMin['Date'], unit='s')
删除秒数,但我收到错误:
Value must be Timedelta, string, integer, float, timedelta or convertible
最佳答案
如果 dtype 已经是 datetime
你可以使用 dt
访问器只返回分钟属性:
In [43]:
df['Date'].dt.minute
Out[43]:
0 33
1 32
2 42
3 41
Name: Date, dtype: int64
如果需要使用 to_datetime
进行转换:
df['Date'] = pd.to_datetime(df['Date'])`
如果日期是字符串并且格式正确,您可以在 :
上拆分并提取倒数第二个拆分:
In [46]:
df['Date'].str.split(':').str[-2]
Out[46]:
0 33
1 32
2 42
3 41
Name: Date, dtype: object
这将返回一个字符串系列,但是,如果您想要整数,则可以使用 astype(int)
转换为 int:
In [47]:
(df['Date'].str.split(':').str[-2]).astype(int)
Out[47]:
0 33
1 32
2 42
3 41
Name: Date, dtype: int32
关于python - 如何去除日期、小时和秒的 Pandas 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41954938/