python - 如何去除日期、小时和秒的 Pandas 日期时间

标签 python python-3.x pandas datetime

如何从 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/

相关文章:

python - 为什么我的不同实例变量在 python 中链接在一起

python - 观察变量何时被删除

python - 在 Pandas 中映射

python - Pandas 使用滚动总和和递减窗口创建新列

python - SQLAlchemy 1.4 关于与关联表的多对多关系重叠关系的警告

python - 带有 GKE 的 GCS,403 写入 GCS 存储桶的权限不足

python - 无法在 Anaconda 上通过 Tensorflow 获取 MNIST 数据集

python-3.x - Gensim Word2Vec : poor training performance.

Python 和 pandas : subtracting and formatting dataframe

python - 使用 python 的 networkX 计算个性化页面排名