gpt4 book ai didi

带有可变文本的 Python strptime

转载 作者:太空狗 更新时间:2023-10-30 02:51:54 26 4
gpt4 key购买 nike

我有一个日期列表作为字符串。它看起来像这样:

[
"January 29-30 Meeting - 2013",
"March 19-20 Meeting - 2013",
"April/May 30-1 Meeting - 2013",
"June 18-19 Meeting - 2013",
"July 30-31 Meeting - 2013",
"September 17-18 Meeting - 2013",
"October 29-30 Meeting - 2013",
"December 17-18 Meeting - 2013"
]

我需要将这些日期解析为datetime 格式。

datetime.strptime("January 29-30 Meeting - 2013", "%B %d-[something] - %Y")
datetime.strptime("January 29-30 Meeting - 2013", "%B [something]-%d [something] - %Y")

有什么方法可以告诉 strptime 在格式说明符中忽略 [something] 中的文本,因为它可以是可变的?是否有可变文本的格式说明符?

最佳答案

strptime 没有通配符指令。您可以在此处查看指令列表 https://docs.python.org/3/library/time.html#time.strftime

解决问题的明智方法是将正则表达式与 strptime 结合使用。 IE。使用正则表达式过滤掉文本并将剩余的受限文本放入 strptime,或者将匹配的组直接传递到 datetime

import re
from datetime import datetime

ss = [
"January 29-30 Meeting - 2013",
"March 19-20 Meeting - 2013",
"April/May 30-1 Meeting - 2013",
"June 18-19 Meeting - 2013",
"July 30-31 Meeting - 2013",
"September 17-18 Meeting - 2013",
"October 29-30 Meeting - 2013",
"December 17-18 Meeting - 2013"
]

FORMAT = '%B %d %Y'

for s in ss:
match = re.search(r"(\w+)\s(\d+)-(\d+)\s.*\s(\d{4})", s)
if match:
dt1 = datetime.strptime(f'{match.group(1)} {match.group(2)} {match.group(4)}', FORMAT)
dt2 = datetime.strptime(f'{match.group(1)} {match.group(3)} {match.group(4)}', FORMAT)

print (dt1, dt2)

请注意,您还有 April/May 30-1 并发症,我没有解决这个问题,因为您没有问这个问题。

不过作为奖励:

for s in ss:
match = re.search(r"((\w+)/)?(\w+)\s(\d+)-(\d+)\s.*\s(\d{4})", s)
if match:
dt1 = datetime.strptime(
f'{match.group(2) if match.group(2) else match.group(3)} {match.group(4)} {match.group(6)}', FORMAT)
dt2 = datetime.strptime(
f'{match.group(3)} {match.group(5)} {match.group(6)}', FORMAT)

print (dt1, dt2)

另外,请注意下面@blhsing 提供的有趣的解决方案,如果有点 hacky,涉及 _strptime.TimeRE。我不建议做那样的事情,但有趣的是知道你实际上可以用这种方式改变 strptime 本身的行为。

关于带有可变文本的 Python strptime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54451081/

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