regex strptime未正确格式化我的日期

vbopmzt1  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(90)

我在想是否有比我聪明的人能看出我做错了什么。
我正在使用正则表达式Map日期格式,我想将日期转换为"%Y-%m-%d"
在使用"%Y-%m-%d %H:%M:%S"进行测试时,我的日期转换不正确。有人能看出我做错了什么吗?我不知道如何处理剩余的未转换数据。
下面是测试代码供您参考。

from datetime import datetime
import re
import pandas as pd

def conv_date(dte: str) -> datetime: #actul is datetime
    acceptable_mappings = {
        "\d{4}-\d{2}-\d{2}": "%Y-%m-%d",
        "\d{4}-\d{2}-\d{2}\s\d{2}\:\d{2}\:\d{2}": "%Y-%m-%d %H:%M:%S",

    }
    for regex in acceptable_mappings.keys():
        if re.match(regex, dte):
            return datetime.strptime(dte, acceptable_mappings[regex])
    raise Exception(f"Expected date in one of supported formats, got {dte}")

def full_list_parse(unclean_list: list) -> list:
    return [conv_date(dte) for dte in unclean_list]

mock_dict = [
    {"name": "xx", "role": "loves only-fans", "date": "2023-07-26 12:46:21"},
    {"name": "dz", "role": "legend", "date": "2023-07-26"},

]

df = pd.DataFrame(mock_dict)

if __name__ == "__main__":
    print(df)
    df['date_clean'] = df['date'].apply(lambda x: conv_date(x))
    print(df)

字符串
我的成果:

ValueError: unconverted data remains:  12:46:21
  name             role                 date
0   xx  loves only-fans  2023-07-26 12:46:21
1   dz           legend           2023-07-26


我想要的结果:

name             role                 date
0   xx  loves only-fans           2023-07-26
1   dz           legend           2023-07-26

o2gm4chl

o2gm4chl1#

你可以先试试pd.to_datetime

df['date'] = pd.to_datetime(df['date'], format='mixed', dayfirst=False)

df['only_date'] = df['date'].dt.date
print(df)

字符串
印刷品:

name             role                date   only_date
0   xx  loves only-fans 2023-07-26 12:46:21  2023-07-26
1   dz           legend 2023-07-26 00:00:00  2023-07-26

相关问题