Home > Enterprise >  The birth date I'm trying to display is not in the format that I want: Day of week, Month Day,
The birth date I'm trying to display is not in the format that I want: Day of week, Month Day,

Time:11-01

I am trying to take user input of a birthday in form MM/DD/YY and change it so it prints day of week, month day, year. I am in an intro class, so I have no experience in this...simple solutions appreciated.

birthday = input("Enter Birthday (MM/DD/YY): ")
birthday = datetime.strptime(birthday, "%m/%d/%y")
if birthday > datetime.now():
    fixed_birth_year = birthday.year - 100
    birthday = datetime(birthday.month, birthday.day, fixed_birth_year)
    birthday = datetime.strftime(birthday, "%A, %B %d, %Y")
print("Birthday: ", birthday)

I don't know what to do with lines 5 and 6. I thought line 6 would be my answer but it prints out as year-month-day hour:minute:second

CodePudding user response:

The year must come first when fixing the datetime year. See help(datetime):

>>> help(datetime)
Help on class datetime in module datetime:

class datetime(date)
 |  datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
    ...

So use the following:

birthday = datetime(fixed_birth_year, birthday.month, birthday.day)

You can also use the datetime.replace method:

birthday = birthday.replace(year=fixed_birth_year)

The indentation is also wrong on the 6th line, so formatting only works when the year needs a correction. 02/28/02 will print incorrectly. The following code fixes both problems and gives examples:

from datetime import datetime

def display(birthday):
    birthday = datetime.strptime(birthday, "%m/%d/%y")
    if birthday > datetime.now():
        fixed_birth_year = birthday.year - 100
        birthday = birthday.replace(year=fixed_birth_year)
    birthday = datetime.strftime(birthday, "%A, %B %d, %Y")
    print("Birthday: ", birthday)

display('02/28/02')
display('02/28/65')

Output:

Birthday:  Thursday, February 28, 2002
Birthday:  Sunday, February 28, 1965
  • Related