首页 > 解决方案 > 需要使用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:])

谢谢你。

标签: pythonreminders

解决方案


我认为最简单的方法是使用你已经导入的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()对象。
  • if3:比较一个块中的两个同类对象,并且
  • 4:返回每个假期前三周的日期列表,其中包含应设置提醒的假期名称。

然后你就准备好了。你可以打电话

ReminderDates = CheckAllHolidays()[0]
ReminderNames = CheckAllHolidays()[1]

然后使用这两个列表来创建您的提醒!ReminderDates将是一个填充有datetime.datetime()对象的数组,并且ReminderNames将是一个填充有字符串值的数组。

很抱歉我的回复有点长,但我真的希望我能帮助你解决你的问题!节日快乐 <3


推荐阅读