【问题标题】:Pandas excel import changes the Date formatPandas excel 导入更改日期格式
【发布时间】:2018-03-21 23:12:52
【问题描述】:

我正在学习 python (3.6 with anaconda) 用于我的学习。

我正在使用 pandas 导入一个包含 2 列的 xls 文件:日期(dd-mm-yyyy)和价格。 但是 pandas 改变了日期格式:

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 的不同方法,但没有解决。

有什么想法吗?

谢谢

【问题讨论】:

  • Excel 中的日期不存储为字符串,它们只是一个数字。当您从 Excel 中提取该数据时,任何格式都会丢失。当你打印它时,Python 会应用它自己的格式。
  • 感谢您提供此信息,反正我的问题已经解决了 ;)

标签: python excel pandas date


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢,它可以与 pd.datetime.strftime(df.iloc[0,1], "%Y-%m-%d") 配合使用
猜你喜欢
  • 2017-10-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
相关资源
最近更新 更多