将列转换为时间戳 - Pandas Dataframe

问题描述 投票:0回答:3

我有一个 Pandas DataFrame,其日期值存储在以下格式的 2 列中:

col1: 04-APR-2018 11:04:29
col2: 2018040415203 

如何将其转换为时间戳。这两列的 Dtype 都是

object

python-3.x pandas datetime type-conversion timestamp
3个回答
43
投票

对于第一种格式,您可以简单地传递 to_datetime,对于后者,您需要显式描述日期格式(请参阅 python 文档中的可用指令表):

In [21]: df
Out[21]:
                   col1           col2
0  04-APR-2018 11:04:29  2018040415203

In [22]: pd.to_datetime(df.col1)
Out[22]:
0   2018-04-04 11:04:29
Name: col1, dtype: datetime64[ns]

In [23]: pd.to_datetime(df.col2, format="%Y%m%d%H%M%S")
Out[23]:
0   2018-04-04 15:20:03
Name: col2, dtype: datetime64[ns]

20
投票

你也可以尝试这些。 尝试在读取文件时传递 infer_datetime_format = True

如果上述方法失败请尝试以下方法

df2 = pd.to_datetime(df.col1)

df2 = pd.to_datetime(df['col1'])
df2

注意上述方法只会将 str 转换为日期时间格式并以 df2 形式返回。简而言之,df2 将只有 str 的日期时间格式,没有列名。如果您想保留数据帧的其他列并希望为转换后的列提供标题,您可以尝试以下操作

df['col1_converetd'] = pd.to_datetime(df.col1)

df['col1_converetd'] = pd.to_datetime(df['col1'])

如果您不想创建数据框或希望将来将转换后的列与数据框的其他属性一起引用,那么这很方便。


4
投票

有几种方法可以将列值转换为时间戳,其中一些方法比其他方法更有效。注意:将

format=
传递给
to_datetime
可以使转换变得非常非常快(参见 this post)。您可以在https://strftime.org/找到所有可能的日期时间格式组合。

from datetime import datetime
x = pd.to_datetime(df['col1'], format='%d-%b-%Y %H:%M:%S')
y = df['col1'].apply(pd.Timestamp)
z = df['col1'].apply(datetime.strptime, args=('%d-%b-%Y %H:%M:%S',))

但最终,所有这些都会产生相同的对象(

x.equals(y) and x.equals(z)
返回
True
),如下所示:

0   2018-04-04 11:04:29
Name: col1, dtype: datetime64[ns]

如果我们检查各个值,它们是相同的(

x[0] == y[0] == z[0]
返回
True
),看起来像

Timestamp('2018-04-04 11:04:29')

如果我们查看源代码

pd.Timestamp
datetime.datetime
的子类,所以所有这些最终都由
datetime.datetime
联系在一起。

© www.soinside.com 2019 - 2024. All rights reserved.