繁体   English   中英

如何将字符串日期列转换为新列中的时间戳 Python Pandas

[英]How to convert string date column to timestamp in a new column in Python Pandas

我有以下示例 dataframe:

d = {'col1': ["2022-05-16T12:31:00Z", "2021-01-11T11:32:00Z"]}
df = pd.DataFrame(data=d)
df

    col1
0   2022-05-16T12:31:00Z
1   2021-01-11T11:32:00Z

我需要第二列(比如col2 ),它将具有来自col1的每个 col1 日期字符串值的相应时间戳值。

如果不使用 for 循环,我该怎么做?

让我们试试to_datetime

df['col2'] = pd.to_datetime(df['col1'])
df
Out[614]: 
                   col1                      col2
0  2022-05-16T12:31:00Z 2022-05-16 12:31:00+00:00
1  2021-01-11T11:32:00Z 2021-01-11 11:32:00+00:00

更新

st = pd.to_datetime('1970-01-01T00:00:00Z')
df['unix'] = (pd.to_datetime(df['col1'])- st).dt.total_seconds()
Out[632]: 
0    1.652704e+09
1    1.610365e+09
Name: col1, dtype: float64

也许试试这个?

import pandas as pd
import numpy as np

d = {'col1': ["2022-05-16T12:31:00Z", "2021-01-11T11:32:00Z"]}
df = pd.DataFrame(data=d)

df['col2'] = pd.to_datetime(df['col1'])
df['col2'] = df.col2.values.astype(np.int64) // 10 ** 9

df

暂无
暂无

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

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