从 pandas 数据框中的日期时间删除时间戳 [英] Removing the timestamp from a datetime in pandas dataframe
问题描述
方案::我有一个数据框,其中包含从excel工作表中检索到的多列.其中一些列是日期:一些仅包含日期(yyyy:mm:dd),有些具有日期和时间戳记(yyyy:mm:dd 00.00.000000).
Scenario: I have a dataframe with multiple columns retrieved from excel worksheets. Some of these columns are dates: some have just the date (yyyy:mm:dd) and some have date and timestamp (yyyy:mm:dd 00.00.000000).
问题:当日期不是我的数据框的索引时,如何从日期中删除时间戳?
Question: How can I remove the time stamp from the dates when they are not the index of my dataframe?
我已经尝试过的操作:来自SO中的其他帖子(如何剥离日期,时间和秒数的熊猫日期时间)我发现:
What I already tried: From other posts here in SO (working with dates in pandas - remove unseen characters in datetime and convert to string and How to strip a pandas datetime of date, hours and seconds) I found:
pd.DatetimeIndex(dfST['timestamp']).date
和
strfitme (df['timestamp'].apply(lambda x: x.strftime('%Y-%m-%d'))
但是当它不是我的数据框的索引时,我似乎找不到一种直接将它们用于所需列的方法.
But I can't seem to find a way to use those directly to the wanted column when it is not the index of my dataframe.
推荐答案
您可以执行以下操作:
dfST['timestamp'] = pd.to_datetime(dfST['timestamp'])
to_datetime()
将推断日期列的格式.如果该列包含非日期值,也可以传递errors='coerce'
.
to_datetime()
will infer the formatting of the date column. You can also pass errors='coerce'
if the column contains non-date values.
完成上述操作后,您将可以创建一个仅包含日期值的新列:
After completing the above, you'll be able to create a new column containing only date values:
dfST['new_date_column'] = dfST['timestamp'].dt.date
这篇关于从 pandas 数据框中的日期时间删除时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!