Pernille
Pernille

Reputation: 1

Problem converting epoch to datetime - python

I have a pandas data frame showing timestamp in epoch. I need to convert it to datetime format. The code looks like this:

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))

The data type comes out as pandas.core.series.Series. I've tried converting it to int using .astype(int) and pd.to_numeric, but neither seems to work. The code returns the following error:

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'>

[error message][1] [1]: https://i.sstatic.net/z6DsF.png

I've been staring myself blind at this for hours. I'm sure I'm missing something simple. Can anyone see what I´m doing wrong? Thanks!

Upvotes: 0

Views: 245

Answers (1)

tintins7a6164
tintins7a6164

Reputation: 188

Sorry for the previous answer, I misread the question. The problem is that the GPSTime is a Panda series. A possible solution would be to use the builtin functions in the Panda library.

time_strs = pd.to_datetime(GPSTime, unit='s').dt.strftime('%Y-%m-%d %H:%M:%S')

Note that this would return a Panda series of the datetime objects represented as strings.

Upvotes: 1

Related Questions