如何在 python 中将任何格式的日期转换为特定格式?



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

您必须使用正则表达式。我在下面写了一个函数,可以完成您要求的一些操作。

它涵盖:

  • 日-月-年
  • 日/月/年
  • 月-日-年
  • 日/月/年

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

我不知道你的输入格式是什么。我假设它是一个数据帧,其中日期列具有一致的格式。否则,此练习是不可能的,因为您可能会有类似"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

最新更新