编程语言
首页 > 编程语言> > python – 将unix时间转换为pandas dataframe中的可读日期

python – 将unix时间转换为pandas dataframe中的可读日期

作者:互联网

我有一个包含unix时间和价格的数据框.我想转换索引列,以便在人类可读日期中显示.

因此,例如我在索引列中的日期为1349633705,但我希望它显示为10/07/2012(或至少10/07/2012 18:15).

对于某些上下文,这里是我正在使用的代码以及我已经尝试过的代码:

import json
import urllib2
from datetime import datetime
response = urllib2.urlopen('http://blockchain.info/charts/market-price?&format=json')
data = json.load(response)   
df = DataFrame(data['values'])
df.columns = ["date","price"]
#convert dates 
df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.index = df.date   

如你所见,我正在使用
df.date = df.date.apply(lambda d:datetime.strptime(d,“%Y-%m-%d”))这里不起作用,因为我使用的是整数,而不是字符串.我想我需要使用datetime.date.fromtimestamp但我不太确定如何将它应用于整个df.date.

谢谢.

解决方法:

这些似乎是自纪元以来的几秒钟.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

标签:python,pandas,dataframe,unix-timestamp
来源: https://codeday.me/bug/20190915/1806165.html