pandas Excel导入更改日期格式 [英] Pandas excel import changes the Date format

查看:74
本文介绍了 pandas Excel导入更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python(带有anaconda的3.6版)进行学习.

Im learning python (3.6 with anaconda) for my studies.

我正在使用熊猫导入带有两列的xls文件:日期(dd-mm-yyyy)和价格. 但是熊猫会更改日期格式:

Im using pandas to import a xls file with 2 columns : Date (dd-mm-yyyy) and price. But pandas changes the date format :

xls_file = pd.read_excel('myfile.xls')
print(xls_file.iloc[0, 0])

我得到了:

2010-01-04 00:00:00

而不是:

04-01-2010     or at least :  2010-01-04  

我不知道为什么添加hh:mm:ss,从Date列的每一行得到相同的结果.我也使用to_datetime尝试了不同的方法,但是并没有解决它.

I dont know why hh:mm:ss is added, I get the same result for each row from the Date column. I tried also different things using to_datetime but it didnt fix it.

有什么主意吗?

谢谢

推荐答案

您需要定义打印datetime值的格式.可能会有一种更优雅的方法来做到这一点,但类似的方法会起作用:

What you need is to define the format that the datetime values get printed. There might be a more elegant way to do it but something like that will work:

In [11]: df
Out[11]:
   id       date
0   1 2017-09-12
1   2 2017-10-20

# Specifying the format
In [16]: print(pd.datetime.strftime(df.iloc[0,1], "%Y-%m-%d"))
2017-09-12

如果您想以特定格式将日期存储为字符串,则还可以执行以下操作:

If you want to store the date as string in your specific format then you can also do something like:

In [17]: df["datestr"] = pd.datetime.strftime(df.iloc[0,1], "%Y-%m-%d")
In [18]: df
Out[18]:
   id       date     datestr
0   1 2017-09-12  2017-09-12
1   2 2017-10-20  2017-09-12

In [19]: df.dtypes
Out[19]:
id                  int64
date       datetime64[ns]
datestr            object
dtype: object

这篇关于 pandas Excel导入更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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