2

I have a pandas.DataFrame indexed by time, as seen below. The time is in Epoch time. When I graph the second column these time values display along the x-axis. I want a more readable time in minutes:seconds.

In [13]: print df.head()

Time
1481044277379    0.581858
1481044277384    0.581858
1481044277417    0.581858
1481044277418    0.581858
1481044277467    0.581858

I have tried some pandas functions, and some methods for converting the whole column, I visited: Pandas docs, this question and the cool site.

I am using pandas 0.18.1

Community
  • 1
  • 1
Andrew
  • 115
  • 1
  • 6
  • Some of the reearch i forgot to mention: I am using pandas 0.18.1, I have read: http://pandas.pydata.org/pandas-docs/version/0.18.1/timeseries.html http://stackoverflow.com/questions/12400256/python-converting-epoch-time-into-the-datetime - but I dont understand what how to implement. – Andrew Feb 11 '17 at 18:27
  • This online converting gives approach - http://www.epochconverter.com/#code – Andrew Feb 11 '17 at 18:36

2 Answers2

3

You can convert an epoch timestamp to HH:MM with:

import datetime as dt
hours_mins = dt.datetime.fromtimestamp(1347517370).strftime('%H:%M')

Adding a column to your pandas.DataFrame can be done as:

df['H_M'] = pd.Series([dt.datetime.fromtimestamp(int(ts)).strftime('%H:%M')
                       for ts in df['timestamp']]).values
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
3

If you read your data with read_csv you can use a custom dateparser:

import pandas as pd

#example.csv
'''
Time,Value
1481044277379,0.581858 
1481044277384,0.581858
1481044277417,0.581858
1481044277418,0.581858
1481044277467,0.581858
'''

def dateparse(time_in_secs):
   time_in_secs = time_in_secs/1000
   return datetime.datetime.fromtimestamp(float(time_in_secs))

dtype= {"Time": float, "Value":float}
df = pd.read_csv("example.csv", dtype=dtype, parse_dates=["Time"], date_parser=dateparse)
print df
ppasler
  • 3,579
  • 5
  • 31
  • 51