从Python中的中文字符串日期中提取日期



给定一个中文日期列如下:

            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时

在这个例子中,汉字年, 月, 日, 时, 分分别表示year, month, day, hour, minute,我想从中提取日期。下面的代码是有效的,但我只是想知道是否可以简化它,尤其是对于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

最新更新