Search code examples
pythonstringdatetimepython-datetime

Convert String to Python datetime Object without Zero Padding


I'm using python 3.5.

I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.

Here is what I've tried.

    date = "09/10/2015 6:17:09 PM"
    date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')

But this gets an error because the hour is not zero padded. The formatting was done per the table on the datetime documentation, which does not allow the hour to have one digit.

I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.

    date = "09/10/2015 6:17:09 PM"
    date = date.split()
    date = date[0] + " 0" + date[1] + " " + date[2]

Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.

Thank you.


Solution

  • There is nothing wrong with this code:

    >>> date = "09/10/2015 6:17:09 PM"
    >>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
    >>> date_obj
    datetime.datetime(2015, 9, 10, 18, 17, 9)
    >>> print(date_obj)
    2015-09-10 18:17:09
    

    The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.

    Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.

    But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:

    >>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
    >>> print(date_str)
    09/10/2015 06:17:09 PM
    
    # or, if you actually want the output format as %d/%m/%Y....
    >>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
    10/09/2015 06:17:09 PM