简体   繁体   English

如果日期字符串的格式不同,则将字符串转换为python中的日期

[英]Convert string to date in python if date string has different format

My data has date variable with two different date formats 我的数据有两个不同日期格式的日期变量

Date
01 Jan 2019
02 Feb 2019
01-12-2019
23-01-2019
11-04-2019
22-05-2019

I want to convert this string into date(YYYY-mm-dd) 我想将此字符串转换为日期(YYYY-mm-dd)

Date
2019-01-01
2019-02-01
2019-12-01
2019-01-23
2019-04-11
2019-05-22

I have tried following things, but I am looking for better approach 我尝试了以下操作,但是我正在寻找更好的方法

df['Date'] = np.where(df['Date'].str.contains('-'), pd.to_datetime(df['Date'], format='%d-%m-%Y'), pd.to_datetime(df['Date'], format='%d %b %Y'))

Working solution for me 我的工作解决方案

df['Date_1']= np.where(df['Date'].str.contains('-'),df['Date'],np.nan)
df['Date_2']= np.where(df['Date'].str.contains('-'),np.nan,df['Date'])
df['Date_new'] = np.where(df['Date'].str.contains('-'),pd.to_datetime(df['Date_1'], format = '%d-%m-%Y'),pd.to_datetime(df['Date_2'], format = '%d %b %Y'))

Just use the option dayfirst=True 只需使用选项dayfirst=True

pd.to_datetime(df.Date, dayfirst=True)

Out[353]:
0   2019-01-01
1   2019-02-02
2   2019-12-01
3   2019-01-23
4   2019-04-11
5   2019-05-22
Name: Date, dtype: datetime64[ns]

My suggestion: Define a conversion function as follows: 我的建议:定义转换函数如下:

import datetime as dt

def conv_date(x):
    try:
        res = pd.to_datetime(dt.datetime.strptime(x, "%d %b %Y"))
    except ValueError:
        res = pd.to_datetime(dt.datetime.strptime(x, "%d-%m-%Y"))
    return res

Now get the new date column as folows: 现在获取新的日期列,如下所示:

df['Date_new'] = df['Date'].apply(lambda x: conv_date(x))

This works simply as expected - 这完全可以按预期工作-

import pandas as pd

a = pd. DataFrame({
        'Date' : ['01 Jan 2019',
                '02 Feb 2019',
                '01-12-2019',
                '23-01-2019',
                '11-04-2019',
                '22-05-2019']
    })
a['Date'] = a['Date'].apply(lambda date: pd.to_datetime(date, dayfirst=True))

print(a)

You can get your desired result with the help of apply AND to_datetime method of pandas, as given below:- 你可以的帮助下得到你想要的结果applyto_datetime大熊猫的方法,下面给出: -

import pandas pd

def change(value):
    return pd.to_datetime(value)

df = pd.DataFrame(data = {'date':['01 jan 2019']})

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

I hope it may help you. 希望对您有帮助。

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

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