DIY打造生日提醒器
生日提醒的核心是当日与下次生日的时间计算,在这里实现。毕竟作为初学时的实操练习,并没有把这个想法完善下去,这时候还没有接触到GUI。
1. datetime
from datetime import date
2. 储存生日信息的字典,储存仅剩10天过生日的信息列表
peers = [] # 储存仅剩10天过生日的朋友信息
birthdays_dat = { # 储存所有生日信息
'友1': '19970509',
'友2': '19971121',
'友3': '19981111',
'友5': '19970508',
'友6': '19710823',
}
3. 将字典中的信息转化
def get_info():
for i in birthdays_dat:
name = birthdays_dat[i]
birthday = date(int(name[0:4]), int(name[4:6]), int(name[6:8]))
print('%s : %s' % (i, birthday), end='\t')
jug_cal(i, birthday) # 调用下一步中的函数
print('-'*80)
4. 将字典中的生日信息和Today比对
def jug_cal(name, birthday):
today = date.today()
while True:
if birthday <= today: # 循环得到该友的下一次生日日期
birthday = birthday.replace(year=birthday.year+1)
else:
time_to_birthday = abs(birthday - today) # 计算到下一次生日的天数
if time_to_birthday.days <= 10: # 判断生日剩余天数,如果<=10,将会添加到peers列表中
emergence_peers(name, birthday, time_to_birthday) # 调用下一步函数
print('The next birthday is %s. %s days left.' % (birthday, time_to_birthday.days))
break
5. 列表添加函数
def emergence_peers(name, birthday, time_to_birthday):
peers.append('%s : %s . % days left.' % (name, birthday, time_to_birthday.days))
6. 运行函数
if __name__ == '__main__':
get_info()
print('\t\t Ten days left emergence peers:')
for i in peers:
print(i)
完整代码
from datetime import date
peers = [] # 储存仅剩10天过生日的朋友信息
birthdays_dat = { # 储存所有生日信息
'友1': '19970509',
'友2': '19971121',
'友3': '19981111',
'友5': '19970508',
'友6': '19710823',
}
def get_info():
for i in birthdays_dat:
name = birthdays_dat[i]
birthday = date(int(name[0:4]), int(name[4:6]), int(name[6:8]))
print('%s : %s' % (i, birthday), end='\t')
jug_cal(i, birthday) # 调用下一步中的函数
print('-'*80)
def jug_cal(name, birthday):
today = date.today()
while True:
if birthday <= today: # 循环得到该友的下一次生日日期
birthday = birthday.replace(year=birthday.year+1)
else:
time_to_birthday = abs(birthday - today) # 计算到下一次生日的天数
if time_to_birthday.days <= 10: # 判断生日剩余天数,如果<=10,将会添加到peers列表中
emergence_peers(name, birthday, time_to_birthday) # 调用下一步函数
print('The next birthday is %s. %s days left.' % (birthday, time_to_birthday.days))
break
def emergence_peers(name, birthday, time_to_birthday):
peers.append('%s : %s . % days left.' % (name, birthday, time_to_birthday.days))
if __name__ == '__main__':
get_info()
print('\t\t Ten days left emergence peers:')
for i in peers:
print(i)
运行结果展示
C:\ProgramData\Anaconda3\envs\WD\python.exe C:/Users/abc/PycharmProjects/WD/xxxxxxx.py
友1 : 1997-05-09 The next birthday is 2021-05-09. 365 days left.
友2 : 1997-11-21 The next birthday is 2020-11-21. 196 days left.
友3 : 1998-11-11 The next birthday is 2020-11-11. 186 days left.
友5 : 1997-05-08 The next birthday is 2021-05-08. 364 days left.
友6 : 1971-08-23 The next birthday is 2020-08-23. 106 days left.
--------------------------------------------------------------------------------
Ten days left emergence peers:
Process finished with exit code 0