1

I have a string that I need to convert to datetime format. The problem is that it doesn't always have the same format. Right now I'm using try, except to try all the formats that I might encounter (see code below). Is there a way to do this generically for all time formats?

import datetime

def get_time(start_time):    
        try:
            start_time = datetime.datetime.strptime(start_time, '%m/%d/%y %H:%M:%S')                                    
            return start_time
        except:
            try:
                start_time = datetime.datetime.strptime(start_time, '%H:%M:%S')                
                return start_time
            except:
                try:
                    start_time = datetime.datetime.strptime(start_time, '%m/%d/%Y %H:%M')                    
                    return start_time
                except:
                    print("Error could not convert datetime format")   
1
  • use list with patterns and for loop. Commented Feb 5, 2017 at 1:02

1 Answer 1

3

I think that dateutil would be very useful for a task like this - it can appropriately parse most formats.

>>> from dateutil import parser
>>> parser.parse(start_time)

Alternatively, I think you have the right idea with try/except statements, however you should just place all of the formats in a list and iterate over the list with a single try-except block instead of the ugly nesting.

formats = ['%m/%d/%y %H:%M:%S', '%H:%M:%S', '%m/%d/%Y %H:%M']               
def get_time(start_time):
    for formt in formats:
        try:
            return datetime.strptime(start_time, formt)
        except ValueError:
            pass
    print('Could not convert datetime format')
    # or raise an error
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.