[英]Problem converting epoch to datetime - python
我有一个 pandas 数据帧,显示时代的时间戳。 我需要将其转换为日期时间格式。 代码如下所示:
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 是熊猫系列。 一个可能的解决方案是使用 Panda 库中的内置函数。
time_strs = pd.to_datetime(GPSTime, unit='s').dt.strftime('%Y-%m-%d %H:%M:%S')
请注意,这将返回以字符串表示的 Panda 系列日期时间对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.