从系列中删除分钟和小时

13

早上好,

我有以下数据框 (年, 月, 日, 小时, 秒):

print(df)

     Date               Price
2018-01-02 09:42:00       2
2018-01-02 09:46:00       4
2018-01-02 10:22:00       6
...

我想要获取,不包括分钟和秒数:

print(final_df)

     Date               Price
2018-01-02                2
2018-01-02                4
2018-01-02                6
...
我已经尝试过:

I tried:

->

我尝试了:

df['Date'] = datetime.datetime.strptime(df['Date'], '%Y-%m-%d').date()

但它报告说"strptime()的第1个参数必须是str类型,而不是Series类型"


请参考此解决方案:https://dev59.com/plcO5IYBdhLWcg3wZQ3X#45860443 - Abhinay
1个回答

19

如果不是日期时间列,则需要使用to_datetimedt.date

print (df.dtypes)
Date     object
Price     int64
dtype: object

df['Date'] = pd.to_datetime(df['Date']).dt.date

print (df.dtypes)
Date     object
Price     int64
dtype: object

print (df['Date'].head().apply(type))
0    <class 'datetime.date'>
1    <class 'datetime.date'>
2    <class 'datetime.date'>
Name: Date, dtype: object

或者如果需要不带有 hours、minutes 和 seconds 的日期时间,请使用 dt.floor

df['Date'] = pd.to_datetime(df['Date']).dt.floor('d')

print (df.dtypes)
Date     datetime64[ns]
Price             int64
dtype: object

print (df['Date'].head().apply(type))
0    <class 'pandas._libs.tslibs.timestamps.Timesta...
1    <class 'pandas._libs.tslibs.timestamps.Timesta...
2    <class 'pandas._libs.tslibs.timestamps.Timesta...
Name: Date, dtype: object
如果是日期时间列:
print (df.dtypes)
Date     datetime64[ns]
Price             int64
dtype: object


df['Date'] = df['Date'].dt.date

df['Date'] = df['Date'].dt.floor('d')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接