Home > Blockchain >  I have this code but i keep getting errors. Not sure how to fix it
I have this code but i keep getting errors. Not sure how to fix it

Time:10-11

**THIS IS WHAT I AM WORKING ON

Write a program that reads dates from input, one date per line. Each date's format must be as follows: March 1, 1990. Any date not following that format is incorrect and should be ignored. Use the find() method to parse the string and extract the date. The input ends with -1 on a line alone. Use the datetime module to get the current date. Ignore any dates that are later than the current date. Output each correct date as: 3/1/1990.

import datetime


def find(in_date):
    
    num_month = dict(January=1, February=2, March=3, April=4, May=5, June=6, July=7, August=8, October=10, September=9,
                     November=11, December=12)

    year = in_date.split(',')[-1].split()
    month = in_date.split(',')[0].split()[0]
    day = in_date.split(',')[0].split()[-1]
    month_num = num_month[month]
    return str(month_num)   '/'   day '/'year
while True:
    user_input = input()
    if user_input == '-1':
        break
    print(find(user_input))

CodePudding user response:

This solution uses datetime module as it states to do in the instructions.

from datetime import datetime

while True:
    user_input = input()
    if user_input == '-1':
        break
    try:
        dt = datetime.strptime(user_input, "%B %d, %Y")
    except:
        continue
    today = datetime.today() 
    if dt < today:
        print(dt.strftime('%m/%d/%Y'))

CodePudding user response:

Your code as presented is very close to working - see the following with two small modifications (commented for clarity)

import datetime


def find(in_date):
    
    num_month = dict(January=1, February=2, March=3, April=4, May=5, June=6, July=7, August=8, October=10, September=9,
                     November=11, December=12)

    year = in_date.split(',')[-1].strip()  # strip() instead of #split()
    month = in_date.split(',')[0].split()[0]
    day = in_date.split(',')[0].split()[-1]
    month_num = num_month[month]
    return str(month_num)   '/'   day   '/'   year  # added a ' ' before year
while True:
    user_input = input()
    if user_input == '-1':
        break
    print(find(user_input))
  • Related