Andrew
Andrew

Reputation: 115

Convert csv column from Epoch time to human readable minutes

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

Upvotes: 2

Views: 2112

Answers (2)

Stephen Rauch
Stephen Rauch

Reputation: 49794

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

Upvotes: 3

ppasler
ppasler

Reputation: 3719

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

Upvotes: 3

Related Questions