【发布时间】:2022-01-01 16:13:34
【问题描述】:
这是我在 txt 文件 (trans.txt) 中的日志示例:
2021 年 7 月 22 日 09:35:54 撤回:RM500
2021 年 7 月 22 日 09:35:54 撤回:RM500
2021 年 8 月 22 日 09:35:54 撤回:RM500
2021 年 8 月 22 日 09:35:54 撤回:RM500
2021 年 9 月 22 日 09:35:54 撤回:RM500
2021 年 9 月 22 日 09:35:54 撤回:RM500
2021 年 9 月 22 日 09:35:54 撤回:RM500
2021 年 10 月 22 日 09:35:54 撤回:RM500
2021 年 10 月 22 日 09:35:54 撤回:RM500
2021 年 11 月 22 日 09:35:54 撤回:RM500
2021 年 11 月 22 日 09:35:54 撤回:RM500
2021 年 12 月 22 日 09:35:54 提现:RM500
2021 年 12 月 22 日 09:35:54 提现:RM500
如何根据月份打印特定范围的日志? 想象一下,如果我想每季度或每半年打印一次日志,而我的电脑当地时间是 11 月。
我希望 python 打印出从 9 月到 11 月的所有日志,因为我想根据我的当地时间每季度打印一次日志。
编辑:
以下是我的尝试,但仍然无法达到我的预期
# ↓Pulls out local time's from user pc
local_timeMonth = time.strftime("%B", obj)
# ↓Opens user's transaction logs and put them in a list
hand1 = open("trans.txt", "r")
list1 = hand1.read().splitlines()
hand1.close()
# ↓Creates a another file to store all logs with the month that is
# intended to be printed and excludes months that are not relevant,
# but all it does is store logs from November back until January
#it excludes December though (Pc local time is November)
for i in range(0, len(list1)):
if local_timeMonth in list1[i]:
test = "\n".join(list1[i::-1])
hand = open("tempLogs.txt", "w")
hand.write(test)
hand.close()
# ↓Place logs only from 3 months into list
f = open("tempLogs.txt", "r")
line_numbers = [0, 1, 2]
lines = []
# ↓Puts specific month's of log in to another list
for i, line in enumerate(f):
if i in line_numbers:
lines.append(line.strip())
elif i > 2:
break
# ↓Print list out into readable format
for i in lines:
print(i)
f.close()
【问题讨论】:
-
您的问题描述很清楚。但是到目前为止,您尝试过什么?
-
对不起,我应该首先包括我的尝试。我已经通过在那里添加我的尝试来编辑问题。谢谢提醒
标签: python python-3.x sorting datetime logging