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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With