Search code examples
pythondatedatetimedatetime-formatpython-datetime

How to convert date format and add hh:mm:ss to it


My issue is that user can input any date format, 12-feb-2015 or 12/10/2015, i need to convert this in below format :

12-feb-2015 00:00:00

this further would be fed in a MySQL query which would then be used to fetch data in given date ranges
so i have 2 questions :

  • is there any standard way to convert any input format to my required one?

  • how can i append hh:mm:ss to it?

i saw lot of methods on SO thread but none seem to help me out.


Solution

  • Normally SO isn't a code writing service but... :)

    This is only a start to what you could do. I'm unaware of any way to have one test catch multiple formats. Instead I've always "gone through" the available formats. Since we're talking about two, here's something to kick-start your thinking:

    from datetime import datetime
    
    def parse_date(thedate):
        result = None
    
        #try each format
        try:
            result = datetime.strptime(thedate, "%d-%b-%Y")
        except ValueError:
            pass
        except:
            raise
    
        # Let the last one "blow" up
        if result is None:
            result = datetime.strptime(thedate, "%d/%m/%Y")
    
        print "{} parsed into {}".format(thedate,result.strftime("%d-%b-%Y %H:%M:%S"))
    

    parse_date("12/10/2015") yields 12/10/2015 parsed into 12-Oct-2015 00:00:00 and parse_date("12-feb-2015") yields 12-feb-2015 parsed into 12-Feb-2015 00:00:00

    That should get you going. Check out the strptime/strftime formats here (scroll down to the strftime function).