Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timestamp string (Unix time) to datetime or pandas.Timestamp

From a source I retrieve some data in JSON format. I want to save this data (measurements in time) as a text file. Repeatedly I want to go the same source and see if new measurements are available, if so I want to add it to the other measurements.

The data I get looks like this:

{"xyz":[{"unixtime":"1458255600","time":"00:00","day":"18\/03","value":"11","paramlabel":"30-500 mHz","popupcorr":"550","iconnr":"7","paramname":"30-500 mHz"},{"unixtime":"1458256200","time":"00:10","day":"18\/03","value":"14","paramlabel":"30-500 mHz","popupcorr":"550","iconnr":"7","paramname":"30-500 mHz"},etc.]}

I load this data into a pandas DataFrame to be able to work with it more easily. When I load this into a dataframe however, all columns are treated as strings. How can I make sure that the unixtime column is treated as a timestamp (such that I can convert to a datetime)?

like image 238
Yorian Avatar asked Mar 23 '16 12:03

Yorian


People also ask

What is the difference between timestamp and datetime in pandas?

Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas. Value to be converted to Timestamp.

Is pandas good for time series?

Pandas was created by Wes Mckinney to provide an efficient and flexible tool to work with financial data. Therefore, it is a very good choice to work on time series. In this post, we will cover some of the functions and techniques that are used to analyze, manipulate, and visualize time series data.

How do I convert a string to a timestamp in Python?

Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.


1 Answers

use to_datetime and pass unit='s' to treat the value as epoch time after converting the dtype to int using astype:

df['unixtime'] = pd.to_datetime(df['unixtime'].astype(int), unit='s')

Example:

In [162]:
pd.to_datetime(1458255600, unit='s')

Out[162]:
Timestamp('2016-03-17 23:00:00')
like image 141
EdChum Avatar answered Sep 22 '22 13:09

EdChum