时间戳字符串(Unix时间)到datetime或pandas.Timestamp [英] timestamp string (Unix time) to datetime or pandas.Timestamp

查看:1571
本文介绍了时间戳字符串(Unix时间)到datetime或pandas.Timestamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从源头我检索一些JSON格式的数据。我想将这些数据(时间的测量)保存为文本文件。反复我想去同一个来源,看看是否有新的测量可用,如果是的话,我想添加到其他测量。



我得到的数据看起来像这样:

  {xyz:[{unixtime:1458255600,time:00:00 day:18/ 03,值:11,paramlabel:30-500 mHz,popupcorr:550,iconnr :30-500 mHz},{unixtime:1458256200,时间:00:10,日:18 \ / 03,值:14 :30-500 mHz,popupcorr:550,iconnr:7,paramname:30-500 mHz}等}} 

我将这些数据加载到大熊猫DataFrame中,以便更轻松地使用它。当我将它加载到数据框中时,所有列都将被视为字符串。如何确保unixtime列被视为时间戳(这样可以转换为datetime)?

解决方案

使用 to_datetime ,并通过 unit ='s'将值转换为 dtype to int using astype

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

示例:

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

输出[162]:
时间戳('2016-03-17 23:00:00')


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

解决方案

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

这篇关于时间戳字符串(Unix时间)到datetime或pandas.Timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆