首页 > 解决方案 > 如何将可能是任何格式的日期转换为python中的特定格式?

问题描述

我想将日期转换为特定的 'yy-mm-dd' 格式。输入可以是任何格式,例如,可以是 2020 年 5 月 26 日或 2020 年 5 月 26 日或 2020 年 5 月 26 日或 2020 年 5 月 26 日或 2020 年 5 月 26 日等。以上所有内容的输出场景应该是 2020-05-26

标签: pythonpython-3.xstringstring-to-datetime

解决方案


您将不得不使用正则表达式。我在下面写了一个函数,它可以完成你所要求的一些事情。

它涵盖:

  • dd-mm-yyyy
  • 日/月/年
  • mm-dd-yyyy
  • 日/月/年

它不包括2020 年5 月 26 日或5 月 26 日(希望有人能提供帮助,因为我没有足够的时间)但我希望这至少是一个合理的开始。如果您知道如何使用正则表达式,则可以在此基础上进行构建。

我不知道你的输入格式是什么。我假设它是一个 DataFrame,其中日期列具有一致的格式。否则这个练习是不可能的,因为你可能有类似“02-02-2020”的东西,这可能意味着“dd-mm-yyyy”或“mm-dd-yyyy”。

此函数检查整个列,获取“最大”日期(希望包含超过 12 的一天)并识别日和月列。然后根据该列的格式,它相应地将其重新格式化为“yyyy-mm-dd”。

import re

def clean_date_format(date_col):

        # replace "-" with "/"
        new_date = (date_col.str.replace('-', '/')).tolist()

        # check if US format
        first2_regex = r'^(\d*)\/.*'
        second2_regex = r'^.*\/(\d*)\/.*'

        r1 = re.compile(first2_regex)
        r2 = re.compile(second2_regex)

        first2_list = set([re.search(r1, x).group(1) for x in new_date])
        second2_list = set([re.search(r2, x).group(1) for x in new_date])

        first2_condition =  max(list(map(int,first2_list))) <= 12 # i.e. first column contains month
        second2_condition =  max(list(map(int,second2_list))) > 12 # i.e. second column contains day

        US_FORMAT = first2_condition & second2_condition


        if US_FORMAT:
            new_date = pd.DataFrame([datetime.strptime(d, "%m/%d/%Y").strftime("%Y-%m-%d") for d in new_date])
        else:
            new_date = pd.DataFrame([datetime.strptime(d, "%d/%m/%Y").strftime("%Y-%m-%d") for d in new_date])
        return new_date

推荐阅读