简体   繁体   English

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

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

I need to merge 2 pandas dataframes together on dates, but they currently have different date types.我需要在日期上将 2 个 Pandas 数据框合并在一起,但它们目前具有不同的日期类型。 1 is timestamp (imported from excel) and the other is datetime.date . 1 是时间戳(从 excel 导入),另一个是datetime.date

Any advice?有什么建议吗?

I've tried pd.to_datetime().date but this only works on a single item(eg df.ix[0,0] ), it won't let me apply to the entire series (eg df['mydates'] ) or the dataframe.我试过pd.to_datetime().date但这仅适用于单个项目(例如df.ix[0,0] ),它不会让我适用于整个系列(例如df['mydates'] ) 或数据框。

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())

比上面简单得多:

df['mydates'].dt.date

For me this works:对我来说这有效:

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

如果您需要datetime.date对象...然后使用Timestamp.date属性获取它们

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

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_pydatetime method to "Convert a Timestamp object to a native Python datetime object". pandas 文档显示了一个pandas.Timestamp.to_pydatetime方法来“将时间戳对象转换为原生 Python 日期时间对象”。

I found the following to be the most effective, when I ran into a similar issue.当我遇到类似问题时,我发现以下方法最有效。 For instance, with the dataframe df with a series of timestmaps in column ts .例如,数据帧df在列ts具有一系列时间映射。

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

This makes the conversion, you can leave out the .date() suffix for datetimes.这进行了转换,您可以.date()日期时间的.date()后缀。 Then to alter the column on the dataframe.然后更改数据框上的列。 Like so...像这样...

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

Assume time column is in timestamp integer msec format假设时间列是时间戳整数毫秒格式

1 day = 86400000 ms 1 天 = 86400000 毫秒

Here you go:干得好:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

我试图将时间戳列转换为日期/时间,这是我想出的:

df['Timestamp'] = df['Timestamp'].apply(lambda timestamp: datetime.fromtimestamp(timestamp))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM