【发布时间】:2022-01-19 12:07:14
【问题描述】:
我有一个显示时代时间戳的熊猫数据框。我需要将其转换为日期时间格式。 代码如下所示:
import pandas as pd
import numpy as np
import datetime
import time
data_all = pd.ExcelFile('testData_02.xls')
data = pd.read_excel(data_all, 'TestData')
GPSTime = data.loc[:,'GpsUtcTime'].astype(int) # In epochs
#GPSTime = pd.to_numeric(GPSTime,errors='coerce')
print(type(GPSTime))
datetime_time = datetime.datetime.fromtimestamp(GPSTime).strftime('%c')
Time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(GPSTime))
数据类型为 pandas.core.series.Series。我尝试使用 .astype(int) 和 pd.to_numeric 将其转换为 int,但似乎都不起作用。代码返回如下错误:
In [8]: %run NKS_combmorc
<class 'pandas.core.series.Series'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\Documents\Data\NKS_combmorc\NKS_combmorc.py in <module>
35 #datetime_time = datetime.datetime.fromtimestamp(GPSTime).strftime('%c')
36 #datetime_time = dates.num2date(GPSTime, tz='UTC')
---> 37 Time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(GPSTime))
38
39
~\Anaconda3\envs\py3\lib\site-packages\pandas\core\series.py in wrapper(self)
139 if len(self) == 1:
140 return converter(self.iloc[0])
--> 141 raise TypeError(f"cannot convert the series to {converter}")
142
143 wrapper.__name__ = f"__{converter.__name__}__"
TypeError: cannot convert the series to <class 'int'>
[错误信息][1] [1]:https://i.stack.imgur.com/z6DsF.png
几个小时以来,我一直在目瞪口呆地盯着自己看。我确定我错过了一些简单的东西。谁能看到我做错了什么? 谢谢!
【问题讨论】:
-
GPSTime的元素长什么样?自纪元(Unix 时间)以来以秒为单位吗?一般来说,你会在 pandas 中使用pd.to_datetime,而不是原生 Python 日期时间方法。
标签: python pandas datetime ipython