Search code examples
pythonexceptiondatetimestrptime

Guessing the date format python


I am writing a method in a Python module which tries to make live easier to the users. This method implements the creation of events in that calendar.

def update_event(start_datetime=None, end_datetime=None, description=None):
'''
Args:
  start_date: string datetime in the format YYYY-MM-DD or in RFC 3339
  end_date: string datetime in the format YYYY-MM-DD or in RFC 3339
  description: string with description (\n are transforrmed into new lines)
'''

If the user specifies the start_date or the end_date a check up should be made in order to determine if the date is in YYYY-MM-DD format or in the datetime RFC 3339 format.

if (start_date is not None):
    # Check whether we have an date or datetime value
    # Whole day events are represented as YYYY-MM-DD
    # Other events are represented as 2014-04-25T10:47:00.000-07:00
    whole_day_event = False
    try:
        new_start_time = datetime.datetime.strptime(start_date,'YYYY-MM-DD')
        # Here the event date is updated
        try:
            new_start_time = datetime.datetime.strptime(start_date,'%Y-%m-%dT%H:%M:%S%z')
            #Here the event date is updated
        except ValueError:
            return (ErrorCodeWhatever)
    except ValueError:
        return (ErrorCodeWhatever)

Is this a good way of doing this? Can I check what kind of date I am receiving in a nicer way? Thanks!


Solution

  • dateutil.parser.parse can be used to attempt to parse strings into datetime objects for you.

    from dateutil.parser import parse
    
    def update_event(start_datetime=None, end_datetime=None, description=None):
        if start_datetime is not None:
            new_start_time = parse(start_datetime)
    
            return new_start_time
    
    d = ['23/04/2014', '24-04-2013', '25th April 2014']
    
    new = [update_event(i) for i in d]
    
    for date in new:
        print(date)
        # 2014-04-23 00:00:00
        # 2013-04-24 00:00:00
        # 2014-04-25 00:00:00