python-3.x - 在Python中从中文字符串日期中提取日期

标签 python-3.x pandas dataframe datetime

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

            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/

相关文章:

python - "_tkinter.TclError: image "pyimage4 "doesn' t 存在”

python-3.x - 带标签的 Python Dataframe 单行

python - 检查数据框中的列是否处于纪元时间会给出不同的结果

python - 如果行出现两次以上,如何删除重复项?

将 NA 替换为 R 中前一行和后一行的值的平均值

python - 多索引数据帧的基于整数的 (K,N) 索引

python - Pandas GroupBy.agg() 抛出 TypeError : aggregate() missing 1 required positional argument: 'arg'

python - 以优雅的方式计算嵌套列表中的元素

python - 在python中重新排列数据框

Python Pandas : How to subtract values in two non-consecutive rows in a specific column of a dataframe from one another