我有一个熊猫的数据框架,显示时代的时间戳。我需要把它转换成日期时间格式。代码如下所示:
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:https://i.stack.imgur.com/z6DsF.png
我已经盯着这个看了好几个小时了。我肯定我错过了一些简单的东西。有人能看到我做错了什么吗?谢谢!
发布于 2021-12-16 11:49:03
对不起,之前的答案,我误解了问题。问题是GPSTime是熊猫系列。一个可能的解决办法是使用熊猫图书馆的内置函数。
time_strs = pd.to_datetime(GPSTime, unit='s').dt.strftime('%Y-%m-%d %H:%M:%S')请注意,这将返回日期时间对象的Panda系列,该对象表示为字符串。
https://stackoverflow.com/questions/70378358
复制相似问题