简体   繁体   English

Pandas:一列中有多种日期格式

[英]Pandas: Multiple date formats in one column

I have two date formats in one Pandas series (column) that need to be standardized into one format (mmm dd & mm/dd/YY)我在一个 Pandas 系列(列)中有两种日期格式,需要标准化为一种格式(mmm dd & mm/dd/YY)

Date日期

Jan 3 1月3日

Jan 2 1月2日

Jan 1 1月1日

12/31/19 19 年 12 月 31 日

12/30/19 19 年 12 月 30 日

12/29/19 19 年 12 月 29 日

Even Excel won't recognize the mmm dd format as a date format.即使是 Excel 也不会将 mmm dd 格式识别为日期格式。 I can change the mmm to a fully-spelled out month using str.replace:我可以使用 str.replace 将 mmm 更改为完整的月份:

df['Date'] = df['Date'].str.replace('Jan', 'January', regex=True) df['Date'] = df['Date'].str.replace('Jan', 'January', regex=True)

But how do I add the current year?但是如何添加当前年份? How do I then convert January 1, 2020 to 01/01/20?那么如何将 2020 年 1 月 1 日转换为 01/01/20?

Have you tried the parse()你试过 parse()

from dateutil.parser import parse
import datetime

def clean_date(text):
  datetimestr = parse(text)
  text = datetime.strptime(datetimestr, '%Y%m%d')
  return text

df['Date'] = df['Date'].apply(clean_date)
df['Date'] = pd.to_datetime(df['Date']) 

If it's in a data frame use this:如果它在数据框中,请使用:

from dateutil.parser import parse
import pandas as pd

for i in range(len(df['Date'])):
    df['Date'][i] = parse(df['Date'][i])
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")

Found the solution (needed to use apply ):找到解决方案(需要使用apply ):

df['date'] = df['date'].apply(dateutil.parser.parse)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM