Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract date from chinese characters string date in Python

Given a chinese date column as follows:

            time
0  2019年6月27日10时
1  2019年8月28日10时
2   2019年8月5日10时30分
3   2019年9月3日10时
4   2019年9月3日10时
5   2019年8月5日10时

In this example, the chinese characters 年, 月, 日, 时, 分 means respectively year, month, day, hour, minute, I want to extract date from it. The code below works, but I just wonder if it's possible to simplify it, especially for str.replace part.

def date_manipulate(x):
    x = x.str.split('日').str[0].add('日')
    #x = x.str.extract(r'([^d]+日)')
    #x = x.str.extract('(.+日)')
    x = x.str.replace('年', '-').str.replace('月', '-').str.replace('日', '')
    x = pd.to_datetime(x, format='%Y-%m-%d', errors='coerce').dt.date
    return x

df[['time']] = df[['time']].apply(date_manipulate)

The desired output will like this, thank you.

            time
0       2019-06-27
1       2019-08-28
2       2019-08-05
3       2019-09-03
4       2019-09-03
5       2019-08-05
like image 526
ah bon Avatar asked Aug 13 '26 00:08

ah bon


1 Answers

For me working with sample dates removed add and change format in to_datetime function:

def date_manipulate(x):
    x = x.str.split('日').str[0]
    x = pd.to_datetime(x, format='%Y年%m月%d', errors='coerce').dt.date
    return x

df[['time']] = df[['time']].apply(date_manipulate)
print (df)
         time
0  2019-06-27
1  2019-08-28
2  2019-08-05
3  2019-09-03
4  2019-09-03
5  2019-08-05
like image 130
jezrael Avatar answered Aug 16 '26 01:08

jezrael