[英]Python print something on a specific day
I want to create a python code that can print messages on specific days for example something like that:我想创建一个 python 代码,可以在特定日期打印消息,例如:
if day == 27.07:
print("Happy Birthday")
I thank you for any help我感谢你的帮助
Here's a way:这里有一个方法:
from datetime import datetime
birthday = '26.07'
if datetime.today().strftime('%d.%m') == birthday:
print("Happy Birthday")
Docs:文件:
Hope this helps希望这可以帮助
from datetime import date
today = date.today()
if today == "2022-07-26":
print("Happy Birthday")
We can do this for a particular day as mentioned above or a range of days if required.如果需要,我们可以在上面提到的特定日期或几天范围内执行此操作。
1. For only One day 1. 仅限一日
Taking a specific date for example "26/07/1999" and lets print happy birthday if today coincides with our specific day.以特定日期为例“26/07/1999”,如果今天与我们的特定日期重合,则打印生日快乐。
from datetime import datetime
birthday = "26/07/1999"
BRDAY = datetime.strptime(birthday, '%d/%m/%Y')
Today = datetime.now()
if(BRDAY.day == Today.day and BRDAY.month == Today.month):
print("Happy Birthday ")
2. For Multiple days 2. 多天
Say, we have a list of days "1/07/1922","15/07/1922","22/07/1922" and "26/07/1922" and we have to print something on those days then we can try:比如说,我们有一个日期列表“1/07/1922”、“15/07/1922”、“22/07/1922”和“26/07/1922”,我们必须在那些日子打印一些东西然后我们可以尝试:
from datetime import datetime
Days = ["1/07/1922","15/07/1922","22/07/1922","26/07/1922"]
BRDAY=[]
for i in range(len(Days)):
var=Days[i]
BRDAY.append(datetime.strptime(var, '%d/%m/%Y'))
Today = datetime.now()
for i in range(len(Days)):
if(BRDAY[i].day == Today.day and BRDAY[i].month == Today.month):
print("Happy Birthday ")
3. To find if there is a specific day in a list of days 3. 查找日期列表中是否有特定日期
Say we have to search for "15/07/1922" in the list of ["1/07/1922","15/07/1922","22/07/1922","26/07/1922"] and if found, python will print Found , we can try the following:假设我们必须在["1/07/1922","15/07/1922","22/07/1922","26/07/1922"] 的列表中搜索“ 15/07/1922”如果找到, python 将打印Found ,我们可以尝试以下操作:
SPECIFIC="15/07/1922"
SPECIFIC=datetime.strptime(birthday, '%d/%m/%Y')
for i in range(len(Days)):
if(SPECIFIC.day == BRDAY[i].day and BRDAY[i].month == SPECIFIC.month):
print("Found")
Run the full program step by step, you'll get it.一步一步运行完整的程序,你会得到它。 Happy Testing快乐测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.