给定一个中文日期列如下:
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时
本例中年、月、日、时、分
分别表示年、月、日、时、分
,我想提取日期从中。
下面的代码有效,但我只是想知道是否可以简化它,尤其是 str.replace
部分。
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)
想要的输出会像这样,谢谢。
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
最佳答案
对我来说,在 to_datetime
函数中删除了 add
和更改 format
示例日期:
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
关于python-3.x - 在Python中从中文字符串日期中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542316/