将列转换为时间戳-Pandas Dataframe
问题描述:
我有一个Pandas数据框,其日期值以以下格式存储在2列中:
I have a Pandas Dataframe that has date values stored in 2 columns in the below format:
Column 1: 04-APR-2018 11:04:29
Column 2: 2018040415203
我该如何转换到一个时间戳。这两个列的数据类型都是Object。
How could I convert this to a time stamp. Datatype of both these column is Object.
答
对于第一种格式,您可以简单地传递to_datetime,对于后者,您需要显式描述日期格式(请参阅python docs ):
For the first format you can simply pass to_datetime, for the latter you need to explicitly describe the date format (see the table of available directives in the python docs):
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]