目录
- 1. 实战
- 1-1 安装依赖
- 1-2 &nbjssp;创建数据表
- 1-3 查询数据
- 1-4 遍历,获取距离今天的天数
- 1-5 组装数据及消息推送
在国内,大部分人都是过农历生日,然后借助日历工具获取农历日期对应的阳历日期,以这一天来过生!
这里还有一个痛点,即:每一年的农历生日对应的阳历日期都不一样
本篇文章将教你利用 python 制作一个简单的生日提醒
1. 实战
具体操作步骤如下
1-1 安装依赖
#安装依赖 pip3installzhdate pip3installpymysql
其中,zhdate 模块用于中国农历、阳历之间的转换,并且支持日期差额计算
项目地址:
https://github.com/CutePandaSh/zhdate
1-2 创建数据表
创建一条数据表
createtablebirthday ( idintauto_increment primarykey, namevarchar(100)notnullcomment'名称', yl_birthvarchar(100)notnullcomment'阴历生日', remarkvarchar(100)nullcomment'备注', is_deleteintdefault0nullcomment'0:正常 1:删除' ) comment'生日';
然后,将需要提醒用户的姓名、农历生日等数据写入
PS:这里阴历生日格式是 mm-dd,比如:10-25
1-3 查询数据
importpymysql
classBirth(object):
def__init__(self):
self.db=pymysql.connect(host='**',
user='root',
password='**',
database='xag')
self.cursor=self.db.cursor()
def__get_births(self):
#获取所有数据
self.cursor.execute("""javascript
selectname,yl_birth,remarkfrombirthdaywhereis_delete=0;""")
datas=list(s开发者_JAV培训elf.cursor.fetchall())
1-4 遍历,获取距离今天的天数
遍历上面的数据,将阴历转为阳历,然后计算出距离今天的天数
fromzhdateimportZhDate
...
def__get_diff(self,birth):
"""
根据农历生日,获取当前日期距离的时间(天)
:param birth:农历生日,格式:10-25
:return:
"""
#1、获取今日的农历日历
now=str(datetime.now().strftime('%Y-%m-%d')).split("-")
#年、月、日
year,month,day=int(now[0]),int(now[1]),int(now[2])
#1、获取阴历生日,转为阳历编程客栈
birth_month=int(birth.split("-")[0].strip())
birth_day=int(birth.split("-")[-1].strip())
birth_ying=ZhDate(year,birth_month,birth_day)
#转为阳历
birjavascriptth_yang=birth_ying.to_datetime()
#2php、计算距离当前日期的时间间隔(天)
today=datetime.now().strftime('%Y-%m-%d')
d1=datetime.strptime(today,'%Y-%m-%d')
diff_day=(birth_yang-d1).days
returndiff_day
...
#遍历数据
foritemindatas:
name=item[0]
birth=item[1]
nickname=item[2]
diff=self.__get_diff(birth)
...
1-5 组装数据及消息推送
通过时间间隔,在提前一周、生日当天做一个提醒
最后,将组装好的消息通过企业微信机器人发送出去
importrequests
importjson
...
defsend_wechat(self,msg:str):
"""发送信息到企业微信"""
#这里填写你的机器人的webhook链接
url='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key**'
headers={"Content-Type":"text/plain"}
data={
"msgtype":"text",
"text":{
"content":msg
}
}
#发送消息
requests.post(url,headers=headers,data=json.dumps(data))
...
以上就是一文教你利用Python制作一个生日提醒的详细内容,更多关于Python生日提醒的资料请关注我们其它相关文章!
加载中,请稍侯......
精彩评论