[英]Convert column of Timestamps to datetime.datetime. Works on 1 row, not on column
I've looked at every answer on this site, including this one: convert timestamp to datetime.datetime in pandas.Series and nothing is working.我查看了该站点上的每个答案,包括这个: 将时间戳转换为 pandas.Series 中的 datetime.datetime并且没有任何效果。 It always returns a Timestamp.
它总是返回一个时间戳。
I have a dataframe with a time
column which contains class 'pandas._libs.tslibs.timestamps.Timestamp'>
values of the format 2022-06-24 15:07:52
.我有一个带有
time
列的数据框,其中包含2022-06-24 15:07:52
格式class 'pandas._libs.tslibs.timestamps.Timestamp'>
值。
I'm trying to use pandas' pd.df.to_sql
function to write my entire dataframe to a MySQL database.我正在尝试使用 pandas 的
pd.df.to_sql
函数将我的整个数据框写入 MySQL 数据库。 I'm running into an error however because the type of the time
column in the database is Datetime
, so I need to convert the Timestamps to Datetime format in the dataframe.但是我遇到了一个错误,因为数据库中
time
列的类型是Datetime
,所以我需要在数据框中将 Timestamps 转换为 Datetime 格式。
I've tried df['time'] = pd.to_datetime(df['time'])
, which returns Timestamps.我试过
df['time'] = pd.to_datetime(df['time'])
,它返回时间戳。
The only thing that worked is df['time'][0].to_pydatetime()
when applied to a single row.当应用于单行时,唯一有效的是
df['time'][0].to_pydatetime()
。 However when I try df['time'] = df['time'].apply(lambda x: x.to_pydatetime())
, it doesn't work.但是,当我尝试
df['time'] = df['time'].apply(lambda x: x.to_pydatetime())
时,它不起作用。 The elements are still Timestamps.元素仍然是时间戳。
I read in another answer somewhere that to_pydatetime
won't work on a Series or column, so I also tried to extract the column as a list, then apply to_pydatetime()
to its elements (which works, each element is converted to datetime.datetime
) and then put that list back into the dataframe.我在另一个答案中
to_pydatetime
不适用于系列或列,因此我还尝试将列提取为列表,然后将to_pydatetime()
应用于其元素(有效,每个元素都转换为datetime.datetime
) 然后将该列表放回数据框中。 However when I do that, each element is converted again to a Timestamp...但是,当我这样做时,每个元素都会再次转换为时间戳...
import pandas as pd
df = pd.DataFrame({'time': [1451602801, 1451606401, 1451610001, 1451613601, 1451617201]})
df['datetime'] = pd.to_datetime(df['time'], unit='s')
print(df)
Output输出
time datetime
0 1451602801 2015-12-31 23:00:01
1 1451606401 2016-01-01 00:00:01
2 1451610001 2016-01-01 01:00:01
3 1451613601 2016-01-01 02:00:01
4 1451617201 2016-01-01 03:00:01
import pandas as pd
df = pd.DataFrame({'time': [1451602801, 1451606401, 1451610001, 1451613601, 1451617201]})
df['datetime'] = pd.to_datetime(df['time'], unit='s')
# Wrap the numpy output as a series and force dtype to object:
df['timestamp'] = pd.Series(df.datetime.dt.to_pydatetime(), dtype='O')
print(type(df.datetime[0]))
print(type(df.timestamp[0]))
Output:输出:
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
<class 'datetime.datetime'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.