【问题标题】:Python Dataframe column of dates - change format to yyyy-mm-ddPython Dataframe 日期列 - 将格式更改为 yyyy-mm-dd
【发布时间】:2020-04-05 04:12:45
【问题描述】:

df['date'] 是我正在使用的列。

“日期”列中的数据采用日/月/年格式,如下所示: 2019 年 7 月 12 日。我将如何修改此列以给我年月日或 2019-07-12?

这是我尝试过的,但仍然无法正常工作: df['date'] = pd.to_datetime(str(df['date']))

【问题讨论】:

标签: python pandas


【解决方案1】:

试试:

df.loc[:,'date'] = pd.to_datetime(df.loc[:,'date'], format="%d/%m/%yyyy")

让我知道它是否有效!

编辑#1

既然“日期”列有多种格式,请尝试:

def date_format(df):
    for index, row in df.iterrows():
        try:
            df.loc[index, row['date']] = pd.to_datetime(df.loc[index, row['date']], format="%d/%m/%yyyy")
        except ValueError as e:
            df.loc[index, row['date']] = pd.to_datetime(df.loc[index, row['date']], format="%m/%d/%yyyy")
    return df

【讨论】:

  • 嗨,我在最后删除了多余的 ),它运行了,但显示如下: ValueError: time data '12/25/2019' does not match format '%d/%m /%yyyy'(匹配)
  • 这意味着“日期”列没有固定格式。有些日期的格式为 - m/d/yyyy。
  • 如果只有两种不同的格式,那么我的解决方案应该可以正常工作!
【解决方案2】:

如果您需要将datetime 转换为其他格式,您可以使用dt.strftime(但请注意,然后列的dtype 将是object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2019-09-09
    相关资源
    最近更新 更多