【问题标题】:How do I change the date format in a dataframe column.如何更改数据框列中的日期格式。
【发布时间】:2016-02-19 21:48:24
【问题描述】:

我在 DataFrame 中有一个日期为 yyyymmdd 格式的列,我需要将其永久更改为 yyyy-mm-dd。

我该怎么做?

【问题讨论】:

  • 列的数据类型是什么? print df[<column name>].dtype 显示了什么?
  • 它是:int64 干杯。

标签: time-series python date


【解决方案1】:

鉴于您在评论中提供的信息,列值不能采用 yyyy-mm-dd 的形式,因为列 dtype 是 int64

您可以将列 dtype 更改为 str,但数据不会有用(即您将无法对其进行任何日期计算,尽管 <> 应该仍然工作,但按字典顺序)。如果这仍然是您想要的,并假设 df 是数据框并且日期列名称是 date

def format_date_col(x):
    x = str(x)
    return '-'.join([x[:4], x[4:6], x[6:]])

    # or maybe like that for better readability:
    x = str(x)
    return '{year}-{month}-{day}'.format(year=x[:4], month=x[4:6], day=x[6:])

df['date'] = df['date'].apply(format_date_col)

更好的方法是使用实​​际日期 dtype:

from datetime import datetime 

def format_date_col(x):
    return datetime.strptime(str(x), '%Y%m%d')

df['date'] = df['date'].apply(format_date_col)

print df['date'].dtype
>> datetime64[ns]

【讨论】:

  • 您的 def format_date_col(x) 完全符合我的需要。非常感谢!
猜你喜欢
  • 2021-04-14
  • 2019-01-20
  • 2015-04-15
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
相关资源
最近更新 更多