簡體   English   中英

如果日期字符串的格式不同,則將字符串轉換為python中的日期

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

我的數據有兩個不同日期格式的日期變量

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

我想將此字符串轉換為日期(YYYY-mm-dd)

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

我嘗試了以下操作,但是我正在尋找更好的方法

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'))

我的工作解決方案

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'))

只需使用選項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]

我的建議:定義轉換函數如下:

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

現在獲取新的日期列,如下所示:

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

這完全可以按預期工作-

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)

你可以的幫助下得到你想要的結果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

希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM