gpt4 book ai didi

python - 使用 Python3 检测日期格式并将它们转换为 MM-DD-YYYY

转载 作者:行者123 更新时间:2023-12-02 05:36:16 24 4
gpt4 key购买 nike

我正在尝试使用 Python 3.6 转换日期格式并使它们在整个文档中统一。
这是我的文档中的日期示例:(由于文档很大,可能还有其他格式。)

9/21/1989
19640430
6/27/1980
5/11/1987
Mar 12 1951
2 aug 2015

我查了 datetime图书馆。但无法理解如何自动检测和更改日期格式。这是我迄今为止检查过的内容:
>>> from datetime import datetime
>>> oldformat = '20140716'
>>> datetimeobject = datetime.strptime(oldformat,'%Y%m%d')
>>> newformat = datetimeobject.strftime('%m-%d-%Y')
>>> print (newformat)
07-16-2014

但我不知道如何让程序自动检测日期模式并将它们转换为单一的统一日期模式,如 mm/dd/yyyy请建议我需要做什么,以便使用 Python 3.6 实现我的目标。

最佳答案

没有通用的 Python 方法可以做到这一点,但我建议使用正则表达式来识别类型,然后正确转换它:

示例 Python

import re
from datetime import datetime

with open("in.txt","r") as fi, open("out.txt","w") as fo:
for line in fi:
line = line.strip()
dateObj = None
if re.match(r"^\d{8}$", line):
dateObj = datetime.strptime(line,'%Y%m%d')
elif re.match(r"^\d{1,2}/", line):
dateObj = datetime.strptime(line,'%m/%d/%Y')
elif re.match(r"^[a-z]{3}", line, re.IGNORECASE):
dateObj = datetime.strptime(line,'%b %d %Y')
elif re.match(r"^\d{1,2} [a-z]{3}", line, re.IGNORECASE):
dateObj = datetime.strptime(line,'%d %b %Y')
fo.write(dateObj.strftime('%m-%d-%Y') + "\n")

示例输入
9/21/1989
19640430
6/27/1980
5/11/1987
Mar 12 1951
2 aug 2015

示例输出
09-21-1989
04-30-1964
06-27-1980
05-11-1987
03-12-1951
08-02-2015

关于python - 使用 Python3 检测日期格式并将它们转换为 MM-DD-YYYY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com