【问题标题】:How to convert a date which maybe in any format to a specific format in python?如何将可能是任何格式的日期转换为python中的特定格式?
【发布时间】:2020-05-26 12:25:31
【问题描述】:

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

【问题讨论】:

  • 您必须处理所有可能的输入格式。我怀疑是否有任何这样的库可以可靠地做到这一点,因为单个输入格式可以评估为多个输出。例如19-03-02 可以评估为(2019 年 3 月 2 日)、(2019 年 2 月 3 日)、(2002 年 3 月 19 日)等。

标签: python python-3.x string string-to-datetime


【解决方案1】:

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

它涵盖:

  • dd-mm-yyyy
  • dd/mm/yyyy
  • mm-dd-yyyy
  • dd/mm/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

【讨论】:

  • 你为什么假设输入是一个DataFrame列?
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
相关资源
最近更新 更多