将当前日期与CSV文件匹配并打印匹配项

时间:2016-09-13 11:19:18

标签: python date csv datetime smtp

嗨所以我正在写一个python脚本来发送生日邮件的那种东西。但我陷入了中间。我有一个包含姓名和生日的csv文件,并且已经编写了一个代码来获取当前日期,

#Import Date
import datetime
CurrentDate = datetime.datetime.now().date()
CurrentDate = CurrentDate.strftime("%d-%B-%Y")
print(CurrentDate)

我的csv文件是

user1,13-September-2016
user2,19-October-2016
user3,13-September-2016
user4,25-August-2016

所以我想要的是将当前日期与此csv的第二列匹配并获取相应列的一个值并将其导出为字符串,就像我从datetime获取CurrentDate一样。如果在相应的日子有多个用户讨厌生日,则应在他们的名字之间打印“和”。我希望我在提出这个问题时没有犯错:)

2 个答案:

答案 0 :(得分:1)

只需将它们分组并输出您想要的任何内容:

import csv
from datetime import datetime
today = datetime.now().date().strftime("%d-%B-%Y")

with open("b.csv") as f:
    has_birthday = [user for user, birthday in csv.reader(f) if birthday == today]
    print(has_birthday)

输出:

['user1', 'user3']

您可以根据has_birthday的长度添加自定义消息:

has_birthday = [user for user, birthday in csv.reader(f) if birthday == today]
frm = "{} have their birthdays today." if len(has_birthday) > 1 else "{} has their birthday today."
print(frm.format(" and ".join(has_birthday or ["Nobody"])))

所以对于一个匹配的生日:

userx has their birthday today.

不止一个:

userx and Usery have their birthdays today.

对于没有用户:

Nobody has their birthday today.

答案 1 :(得分:0)

谢谢大家,所以在完成一些工作后,在得到所有帮助后,我能够解决这个问题

enumQueryString