python - 需要使用python输出txt文件中剩余的假期
问题描述
节日快乐!
我正在做一个需要提前 3 周发送公共假期提醒的项目。我已经完成了这部分,现在需要添加一个函数,该函数除了即将到来的假期外,还将发送该年剩余的假期。任何有关如何解决此问题的提示或建议将不胜感激,因为我是编码新手!
这是我现在拥有的代码:
import datetime
from datetime import timedelta
import calendar
import time
import smtplib as smtp
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.message import EmailMessage
holidayFile = 'calendar.txt'
def run(input):
checkTodaysHolidays()
def checkTodaysHolidays():
file = open(holidayFile, 'r')
date = (datetime.date.today() + datetime.timedelta(days=21)).strftime('%Y/%m/%d')
publicHolidayName = ''
for line in file:
if date in line:
publicHolidayName = " ".join(line.split()[1:])
谢谢你。
解决方案
我认为最简单的方法是使用你已经导入的datetime
和模块。timedelta
我会将文本文件中的数据转换为数组,然后构建一个函数,将今天的日期与此列表中的假期进行比较。
holidayFile = open('calendar.txt', 'r')
holidayLines = holidayFile.readlines()
holidayFile.close()
holidayNames = []
holidayDates = []
for x in range(0, len(holidayLines) ):
# ... Get the date, first
this = holidayLines[x].split(" ") # since we know they're formatted "YYYY/MM/DD Name of Holiday"
rawdate = this[0]
datechunks = rawdate.split("/") # separate out the YYYY, MM, and DD for use
newdate = (datechunks[0] ,datechunks[1] , datechunks[2])
holidayDates.append(newdate)
# ... then get the Name
del this[0] # remove the dates from our split array
name = "".join(this)
holidayNames.append(name)
所以在我们的函数之前的块中,我:
- 1:打开文件并存储每一行,然后关闭它。
- 2:遍历每一行并分离出日期,并将touples存储在一个数组中。
- 3:将名称保存到单独的数组中。
然后我们进行比较。
def CheckAllHolidays():
returnNames = [] # a storage array for the names of each holiday
returnDays = [] # a storage array for all the holidays that are expected in our response
today = datetime.datetime.now()
threeweeks = timedelta(weeks=3)
for x in range(0, len(holidayDates) ):
doi = holidayDates[x] # a touple containing the date of interest
year = doi[0]
month = doi[1]
day = doi[2]
holiday = datetime.datetime(year, month, day)
if holiday > today:
# convert the holiday date to a date three weeks earlier using timedelta
returnDays.append( holiday - threeweeks )
returnNames.append( holidayNames[x] )
else:
pass # do nothing if date has passed
return(returnDays, returnNames)
我在这里所做的是:
- 1:在函数内部创建一个数组来存储我们的假期名称。
- 2:将前一个数组中的日期转换为
datetime.datetime()
对象。 if
3:比较一个块中的两个同类对象,并且- 4:返回每个假期前三周的日期列表,其中包含应设置提醒的假期名称。
然后你就准备好了。你可以打电话
ReminderDates = CheckAllHolidays()[0]
ReminderNames = CheckAllHolidays()[1]
然后使用这两个列表来创建您的提醒!ReminderDates
将是一个填充有datetime.datetime()
对象的数组,并且ReminderNames
将是一个填充有字符串值的数组。
很抱歉我的回复有点长,但我真的希望我能帮助你解决你的问题!节日快乐 <3
推荐阅读
- java - 如何使用函数返回 Iterable?
- java - 如何从字符串图像中获取像素 RGB 值?.get 不适用于 imageLoader(处理中)
- swift - 在这种情况下,“Promise”对于类型查找是模棱两可的
- php - 如何添加具有不同whenLoaded关系的相同数组键?
- google-visualization - 更改 TreeMap 的选择事件侦听器
- c# - Quartz.net 3.0.6 和 system.data.sqlite 1.0.109,没有提供者“SQLite-10”的元数据信息
- java - 合并排序返回由第一个条目的多个重复项组成的 ArrayList,而不是排序的 ArrayList
- java - 在列表中查找增量之前的最小值(并更新它)
- micronaut - Micronaut 控制器中的默认处理程序
- java - 如何在 Java 中合并两个对象?