[英]How to identify multiple dates within a python string?
For a given string, I want to identify the dates in it.对于给定的字符串,我想确定其中的日期。
import datefinder
string = str("/plot 23/01/2023 24/02/2021 /cmd")
matches = list(datefinder.find_dates(string))
if matches:
print(matches)
else:
print("no date in string")
Output: Output:
no date in string
However, there are clearly dates in the string.但是,字符串中显然有日期。 Ultimately I want to identify which date is the oldest by putting in a variable Date1, and which date is the newest by putting in a variable Date2.
最后,我想通过放入变量 Date1 来确定哪个日期最早,通过放入变量 Date2 来确定哪个日期是最新的。
I believe that if a string contains multiple dates, datefinder is unable to parse it.我相信如果一个字符串包含多个日期,datefinder 将无法解析它。 In your case, splitting the string using
string.split()
and applying the find_dates
method should do the job.在您的情况下,使用
string.split()
拆分字符串并应用find_dates
方法应该可以完成这项工作。
You've only given 1 example, but based on that example, you can use regex.您只给出了 1 个示例,但基于该示例,您可以使用正则表达式。
import re
from datetime import datetime
string = "/plot 23/01/2023 24/02/2021 /cmd"
dates = [datetime.strptime(d, "%d/%m/%Y") for d in re.findall(r"\d{2}/\d{2}/\d{4}", string)]
print(f"earliest: {min(dates)}, latest: {max(dates)}")
Output Output
earliest: 2021-02-24 00:00:00, latest: 2023-01-23 00:00:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.