Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unix epoch time to datetime in Pandas

I have been searching for a long time to find a solution to my problem.

I get the data from the column I want using the below code

import pandas as pd
df = pd.read_excel("Live_data_test.xlsx","Sheet1")

number_of_entries = len(df.loc[:, 'Time'])
number_of_entries_last_3 = number_of_entries - 3
unix_x1 = df.loc[number_of_entries_last_:number_of_entries, 'Time']
print(unix_x1)

I get the output

10    1.513753e+09
11    1.513753e+09
12    1.513753e+09
Name: Time, dtype: float64

I want to convert this time into readable time so I can input it into the x axis of a matplotlib graph.

real_x1 = datetime.datetime.strptime(str(unix_x1), '%Y-%m-%d %H:%M:%S')

I get the error

ValueError: time data '10    1.513753e+09\n11    1.513753e+09\n12    1.513753e+09\nName: Time, dtype: float64' does not match format '%Y-%m-%d %H:%M:%S'

how do I get this unix time to output into a readable format for a user?

I am a little new to code so if you answer, could you please explain the reasoning if you can?

like image 899
smashed__ Avatar asked Apr 20 '18 20:04

smashed__


People also ask

How do I convert a column of epoch time in python?

The pd. to_datetime() function can be used to convert a column or a series object containing epoch time to readable date and time values in datetime type format. We can also specify the unit of the epoch time using the unit parameter.

How do I convert a timestamp to a date in python?

Converting timestamp to datetime We may use the datetime module's fromtimestamp() method to convert the timestamp back to a datetime object. It returns the POSIX timestamp corresponding to the local date and time, as returned by time. time().

What is pandas datetime format?

The date-time default format is “YYYY-MM-DD”. Hence, December 8, 2020, in the date format will be presented as “2020-12-08”. The datetime format can be changed and by changing we mean changing the sequence and style of the format.


1 Answers

Pandas can read unix epoch time, use unit parameter

pd.to_datetime('1.513753e+09', unit = 's')

Timestamp('2017-12-20 06:56:40')

You can pass your column using

pd.to_datetime(df[<your_datetime_column>], unit = 's')
like image 123
Vaishali Avatar answered Oct 12 '22 12:10

Vaishali