节日快乐!
我正在做一个项目,需要提前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)
所以在我们函数之前的块中,I:
- 1:打开文件并存储每一行,然后关闭它
- 2:遍历每一行并分离出日期,并将数字存储在一个数组中
- 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()
对象 - 3:比较
if
块中的两个同类对象 - 4:在每个假期前三周返回一份日期列表,其中包含应设置提醒的假期名称
然后你就准备好了。你可以打电话给
ReminderDates = CheckAllHolidays()[0]
ReminderNames = CheckAllHolidays()[1]
然后使用这两个列表创建提醒!ReminderDates
将是用datetime.datetime()
对象填充的数组,而ReminderNames
将是用字符串值填充的数组。
很抱歉我的回复有点长,但我真的希望我能帮助你解决你的问题!节日快乐<3