import os, datetime
content = os.listdir("when")
print(content)
#this print...
#['2022_-_12_-_29 12pp33 am _--_ 2023_-_01_-_25 19pp13 pm.txt', '2023-02-05 00pp00 am.txt']
for i in range(len(content)):
content[i] = content[i].replace("_-_", "-").replace("pp", ":")
print(content) #I prepare the input to use it to search
#this print...
#['2022-12-29 12:33 am _--_ 2023-01-25 19:13 pm.txt', '2023-02-05 00:00 am.txt']
input_to_search_in_folder = "2022_-_01_-_05 12:33 am" #file data to find in the 'when' folder
我已经将:
更改为pp
(指点对点),因为不能将:
放在文件夹或/和文件中,至少在Windows中不能
2022_-_12_-_29 12pp33 am _--_ 2023_-_01_-_25 19pp13 pm
initial date _--_ final date
在这种情况下,input_to_search_in_folder = "2022_-_01_-_05 12:33 am"
与具有特定日期名称的文件不匹配,但如果它属于文件名'2022_-_12_-_29 12pp33 am _--_ 2023_-_01_-_25 19pp13 pm.txt'
中指定的天数间隔
我如何验证这个日期"2022_-_01_-_05 12:33 am"
是否属于那个时间间隔'2022_-_12_-_29 12pp33 am _--_ 2023_-_01_-_25 19pp13 pm'
,或者它是否是这个日期'2023-02-05 00:00 am'
?
如果验证成功,程序应该打印该.txt文件中的内容(在本例中是2022_-_12_-_29 12pp33 am _--_ 2023_-_01_-_25 19pp13 pm.txt
文件)
text_file = open("when/" + , "r")
data_inside_this_file = text_file.read()
text_file.close()
#And finally prints the content of the .txt file that matches the date specified in the 'input_to_search_in_folder' variable
print(repr(data_inside_this_file))
2条答案
按热度按时间ajsxfq5m1#
我会彻底清理字符串,将它们转换为datetime对象(因为它们可以相互比较),然后比较,您就得到了结果,可以对它做任何事情:
ryoqjall2#
一种方法是使用regex提取日期,然后像mrblue6的答案那样将它们转换为date:
输出: