如何使用熊猫安全地将以字符串表示的日期的列转换为unix时间戳?

问题描述 投票:2回答:1

我有以下数据框:

       dteday

0      2011-01-01
1      2011-01-02
2      2011-01-03
3      2011-01-04
4      2011-01-05
5      2011-01-06
6      2011-01-07
7      2011-01-08
8      2011-01-09
9      2011-01-10
10     2011-01-11
11     2011-01-12
12     2011-01-13
13     2011-01-14
14     2011-01-15
15     2011-01-16
16     2011-01-17

并且要将此列转换为该日期的Unix时间戳列。

我尝试过,但是遇到下一个错误:

df['tmstamp'] = df.dteday.astype(np.int64)

错误:ValueError: invalid literal for int() with base 10: '2011-01-01'

我在任何地方都找不到相同的问题。有什么问题?谢谢。

python pandas datetime-format unix-timestamp
1个回答
1
投票

看起来您当前的代码正在尝试将字符串2011-01-01直接转换为整数,即np.int64。解析/转换失败,因此您看到一个错误。

您可以使用pd.to_datetime()方法首先将列中的字符串值转换为datetime对象。 (Docs)。然后,您可以将类型转换为np.int64

给出以下数据框:

        dates
0  2011-01-01
1  2011-01-02
2  2011-01-03
3  2011-01-04
4  2011-01-05

尝试一下:

df['timestamp'] = pd.to_datetime(df['dates']).astype(np.int64)

输出:

        dates            timestamp
0  2011-01-01  1293840000000000000
1  2011-01-02  1293926400000000000
2  2011-01-03  1294012800000000000
3  2011-01-04  1294099200000000000
4  2011-01-05  1294185600000000000
© www.soinside.com 2019 - 2024. All rights reserved.