Pandas在DatetimeIndex转换时引发值错误

2024-04-18 23:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将所有ISO-8601格式的值转换为Unix值。不知为什么这条线

a_col = pd.DatetimeIndex(a_col).astype(np.int64)/10**6

引发错误

ValueError: Unable to convert 0 2001-06-29

... (Abbreviated Output of Column

Name: DateCol, dtype: datetime64[ns] to datetime dtype

这很奇怪,因为我保证每个值都在日期时间。日期时间格式如下:

^{pr2}$

时代是日期时间。日期时间. 在

当我检查给我一个错误的列的数据类型时,它是“object”,这正是我要检查的内容。我有什么遗漏吗?在


Tags: to格式错误np时间unixisocol
1条回答
网友
1楼 · 发布于 2024-04-18 23:27:24

假设您的时区是美国/东方(基于您的数据集),并且您的数据帧名为df,请尝试以下操作:

import datetime as dt
from time import mktime
import pytz

df['Job Start Date'] = \
    df['Job Start Date'].apply(lambda x: mktime(pytz.timezone('US/Eastern').localize(x)
                                         .astimezone(pytz.UTC).timetuple()))

>>> df['Job Start Date'].head()
0     993816000
1    1080824400
2    1052913600
3    1080824400
4    1075467600
Name: Job Start Date, dtype: float64

您首先需要使您的“原始”日期时间对象能够感知时区(美国/东方),然后将它们转换为UTC。最后,将新的支持UTC的datetime对象作为时间表从time模块传递给^{}函数。在

相关问题 更多 >