检查字典是否包含日期和计划

时间:2015-10-29 16:27:09

标签: python python-3.x python-3.3

所以我试图创建一个函数来检查函数的内容是否为真:

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)
''

我该怎么写这样的功能?我遇到的问题是如何制作字符串或如何查看日期的字符串是否格式为'YYYY-MM-DD'。

3 个答案:

答案 0 :(得分:1)

以下代码使用strptime来解析日期,如果解析失败,则它不是正确的日期字符串。然后它检查日期是否已经在日历字典中,以查看是否附加或添加第一个条目。

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 ''

答案 1 :(得分:0)

请注意:https://docs.python.org/2/library/time.html#time.strptime

strptime提供所需格式,如果字符串未按您的要求格式化,则会出现异常

答案 2 :(得分:-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"