【问题标题】:How can I reformat date from day-month-year to year-month-day?如何将日期从日月年重新格式化为年月日?
【发布时间】:2017-01-05 21:08:20
【问题描述】:

我的目标是删除索引并更改日期格式。这是数据框:

       Date    tsla    goog    aapl   msft
0    30-Dec-16  217.50  782.78  117.20  62.99
1    29-Dec-16  219.20  785.93  117.11  63.20
2    28-Dec-16  223.80  794.23  118.02  63.40
3    27-Dec-16  222.25  797.86  117.80  64.07
4    23-Dec-16  213.45  792.74  116.52  63.54
5    22-Dec-16  209.99  793.32  116.51  64.10
6    21-Dec-16  212.23  796.68  117.40  63.70
7    20-Dec-16  209.00  798.65  117.50  63.80

这是我想要的样子:

        Date    tsla    goog    aapl   msft
   2016-12-30  217.50  782.78  117.20  62.99
   2016-12-29  219.20  785.93  117.11  63.20
   2016-12-28  223.80  794.23  118.02  63.40
   2016-12-27  222.25  797.86  117.80  64.07
   2016-12-23  213.45  792.74  116.52  63.54
   2016-12-22  209.99  793.32  116.51  64.10
   2016-12-21  212.23  796.68  117.40  63.70
   2016-12-20  209.00  798.65  117.50  63.80

我尝试了我在这里找到的 Reformatting a list of date strings to day, month, year in Python:

dfTSLA = [datetime.datetime.strptime(str(i), '%d-%m-%y').strftime('%y-%m-%d') for i in dfTSLA]

但我收到错误“时间数据 '\ufeffDate' 与格式 '%d-%m-%y' 不匹配”,我猜这是有道理的。不知道该怎么做,因为月份是一个字符串

【问题讨论】:

  • 你做过什么或尝试过什么?
  • 您不会将day-month-year 更改为year-month-day,而是将day-month_name-short_year 更改为long_year-month_number-day`。第一个版本,您可以使用字符串拆分和连接。
  • 您无法从数据框中删除索引 - 它始终存在。您可以在没有索引的情况下保存在文件中,或者在没有索引的情况下呈现 HTML,或者在没有索引的情况下使用 print()。
  • 我已经尝试了我在这里找到的 stackoverflow.com/questions/32258915/…,所以使用 strptime()。但问题是月份是我数据框中的一个字符串。 dfTSLA = [datetime.datetime.strptime(str(i), '%d-%m-%y').strftime('%y-%m-%d') for i in dfTSLA],向我抛出错误“时间数据 '\ufeffDate' 与格式 '%d-%m-%y' 不匹配”
  • 您是否尝试将标题行解析为包含日期?

标签: python pandas dataframe


【解决方案1】:

你可以这样做

如果要将类型改为str

df=pd.DataFrame(["30-Dec-16"],columns=['Date'])
df['Date']=pd.to_datetime(df['Date']).map(lambda x: x.strftime('%Y-%m-%d'))

如果要保留 datetime64 类型

df['Date']=pd.to_datetime(df['Date']).dt.normalize()

【讨论】:

  • 我不会将日期时间转换为字符串。如果你想摆脱时间部分,你可以这样做:df['Date']=pd.to_datetime(df['Date']).dt.normalize()
  • 无论出于何种原因,我的 .dt 都无法正常工作。它给了我一些奇怪的错误。但很高兴知道!
  • 试试这个:pd.to_datetime(df['Date']).normalize()
  • 你可以这样做将数据设置为索引:df.set_index(['Date'], inplace=True)
猜你喜欢
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多