📜  Python程序查找您出生的同一天的生日

📅  最后修改于: 2022-05-13 01:55:14.260000             🧑  作者: Mango

Python程序查找您出生的同一天的生日

编写一个程序来查找在您出生的同一天给定年份的生日。让输入的格式为:YYYY-MM-DD

例子:

推荐:请先在{IDE}上尝试您的方法,然后再继续解决。

创建的函数:

  • split_date(birthdate):此函数将用户给定的日期拆分为年、月和日。
  • get_birthday(birthdate):该函数用于返回用户出生的星期几。
  • true_birthdays(birthdate):此函数用于返回与用户出生同一周的日期列表。

要查找与用户出生同一天的生日,上述三种方法将对我们有所帮助。首先,用户输入日期, split_date()函数将日期拆分为年、月和日。然后函数get_birthday()将用于查找该特定日期的工作日。最后, true_birthdays()函数将用于查找具有相同工作日的所有日期的列表。在此函数中,for 循环将从出生年份迭代到特定年份,并检查任何特定年份的生日是否具有相同的工作日。如果工作日相同,则该日期将添加到日期列表中。

下面是实现。

import datetime
import calendar
  
weekdays = ["Monday", "Tuesday", "Wednesday", 
           "Thursday", "Friday", "Saturday", "Sunday"]
     
  
# get_birth day
def split_date(birthday):
  
    # Split it to year, month and day
    year, month, day = birthday.split('-')    
    return year, month, day
      
  
def get_birthday(birthday):
  
    year, month, day = split_date(birthday)
  
    # Get a date object for the day of birth
    bdate = datetime.datetime(int(year), int(month), int(day))
  
    # Get the integer weekday for the day of birth
    weekday = bdate.weekday()
  
    # Tell the user
    day = weekdays[weekday]
  
    return day   
  
  
def listToString(x):
  
    # initialize an empty string 
    String = " " 
  
    # return string   
    return (String.join(x))
  
  
def true_birthdays(birthdate):
    year, month, day = split_date(birthdate)
  
    # get the year from birthday
    year = birthdate[:4].split('-')
  
    # convert list to string   
    year = listToString(year)
  
    # get the weekday you are born
    d_day = get_birthday(birthdate) 
  
    # list of true birthdate[birthday that have same 
    # weekday as the day you were born]    
    true_BD = [] 
      
    j = 0
  
    for i in range(int(year), 2050):
  
        # add + j to birth year 
        new_year = int(year)+j 
  
        # construct new birthday
        new_birthday = str(str(new_year)+"-"+month+"-"+day) 
  
        # get weekday of the new birthday
        new_d_day = get_birthday(new_birthday)
  
        # if birthday that have same weekday 
        # as the day you were born
        if d_day == new_d_day: 
  
        # add to the list of true birthdate
            true_BD.append(new_birthday)
        else:
            pass
        j += 1
  
    return true_BD
  
  
def main():
  
    # Get the birth date
    birthdate = "1996-11-12"
  
    # year_limit = input("search limit from your birthday- ")
    dates = true_birthdays(birthdate)  
      
    print(dates)
      
  
# Driver's code
main()

输出: