-1

So I am trying to create a function that checks whether or not the contents of a function is true:

def command_add(date, event, calendar):

    '''
    Add event_details to the list at calendar[date]
    Create date if it was not there

    :param date: A string  as "YYYY-MM-DD"
    :param event: A string describing the event
    :param calendar: The calendars database
    :return: a string indicating any errors, "" for no errors
    '''
>>> calendar == {'2015-10-20': ['Python']}
True
>>> command_add("2015-11-01", "Computer Science class", calendar)
''

How would I write such a function? The problem I'm having is how to make the string or how to see if the string for the date is in the format 'YYYY-MM-DD'.

Alexander
  • 105,104
  • 32
  • 201
  • 196
Ez2Earn
  • 27
  • 1
  • 8

3 Answers3

1

The following code uses strptime to parse the date, if the parsing fails it is not a proper date string. Then it checks if the date is already in the calendar dict or not to see whether to append or add the first entry.

from datetime import datetime

def command_add(date, event, calendar):

    '''
    Add event_details to the list at calendar[date]
    Create date if it was not there

    :param date: A string  as "YYYY-MM-DD"
    :param event: A string describing the event
    :param calendar: The calendars database
    :return: a string indicating any errors, "" for no errors
    '''
    try:
        datetime.strptime('%Y-%m-%d', date):
    except ValueError:
        return 'Error parsing date'
    else:
        if date in calendar:
            calendar[date].append(event)
        else:
            calendar[date] = [event]

    return ''
Diego Allen
  • 4,623
  • 5
  • 30
  • 33
  • 1
    Suggest you use `except ValueError:` — bare `except` clauses are generally a bad idea since they trap every possible exception often hiding other problems with the code. – martineau Oct 29 '15 at 16:43
0

Look at: https://docs.python.org/2/library/time.html#time.strptime

Give strptime the wanted format and if string is not formatted as you wanted you will get an exception

Guy Segev
  • 1,757
  • 16
  • 24
-1
from datetime import datetime

def command_add(date, event, calendar):
    # Your Code

calendar = {'2015-10-20': ['Python']}
try:
    Date = "2015-11-01"
    date_object = datetime.strptime(Date, '%Y-%m-%d')
    command_add(Date, "Computer Science class", calendar)
except:
    print "Date Format is not correct"
Shahriar
  • 13,460
  • 8
  • 78
  • 95