Python 如何在 Pandas 数据框中将时间戳转换为 datetime.date?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41783003/
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-08-20 01:36:19  来源:igfitidea点击:

How do I convert timestamp to datetime.date in pandas dataframe?

pythondatedatetimepandas

提问by Afo B

I need to merge 2 pandas dataframes together on dates, but they currently have different date types. 1 is timestamp (imported from excel) and the other is datetime.date.

我需要在日期上将 2 个 Pandas 数据框合并在一起,但它们目前具有不同的日期类型。1 是时间戳(从 excel 导入),另一个是datetime.date.

Any advice?

有什么建议吗?

I've tried pd.to_datetime().datebut this only works on a single item(e.g. df.ix[0,0]), it won't let me apply to the entire series (e.g. df['mydates']) or the dataframe.

我试过,pd.to_datetime().date但这仅适用于单个项目(例如df.ix[0,0]),它不会让我应用于整个系列(例如df['mydates'])或数据框。

回答by Afo B

I got some help from a colleague.

我得到了一位同事的帮助。

This appears to solve the problem posted above

这似乎解决了上面发布的问题

pd.to_datetime(df['mydates']).apply(lambda x: x.date())

pd.to_datetime(df['mydates']).apply(lambda x: x.date())

回答by piRSquared

If you need the datetime.dateobjects... then get them through with the .dateattribute of the Timestamp

如果您需要的datetime.date对象......然后让他们通过与.date的属性Timestamp

pd.to_datetime(df['mydates']).date

回答by codingatty

Another question was marked as dupe pointing to this, but it didn't include this answer, which seems the most straightforward (perhaps this method did not yet exist when this question was posted/answered):

另一个问题被标记为dupe指向这个,但它没有包含这个答案,这似乎是最直接的(也许这个方法在发布/回答这个问题时还不存在):

The pandas doc shows a pandas.Timestamp.to_pydatetimemethod to "Convert a Timestamp object to a native Python datetime object".

pandas 文档展示了pandas.Timestamp.to_pydatetime一种“将时间戳对象转换为原生 Python 日期时间对象”的方法。

回答by BrotherHyman

I found the following to be the most effective, when I ran into a similar issue. For instance, with the dataframe dfwith a series of timestmaps in column ts.

当我遇到类似问题时,我发现以下方法最有效。例如,数据df框在 column 中有一系列时间映射ts

df.ts.apply(lambda x: pd.datetime.fromtimestamp(x).date())

This makes the conversion, you can leave out the .date()suffix for datetimes. Then to alter the column on the dataframe. Like so...

这进行了转换,您可以省略.date()日期时间的后缀。然后更改数据框上的列。像这样...

df.loc[:, 'ts'] = df.ts.apply(lambda x: pd.datetime.fromtimestamp(x).date())

回答by Saxasmu

For me this works:

对我来说这有效:

from datetime import datetime
df[ts] = [datetime.fromtimestamp(x) for x in df[ts]]