Search code examples
pythondatetimeodoo-11

How to convert string into datetime in Python


i have concatenated

date(date field)
time(float)
date_time_to(Char)

i am getting output in this format "2018-10-09 20.00".

I need output in this format '%m/%d/%Y %H:%M:%S'

I used "obj.date_time_to = datetime.strptime(self.date_time_to, "%m/%d/%Y %H:%M:%S.%f")"

i am getting

ValueError: time data '2018-10-09 20.00' does not match format '%m/%d/%Y %H:%M:%S.%f'

Solution

  • You need to parse the string with the right format:

    from datetime import datetime
    
    input = "2018-10-09 20.00"
    #        ^^^^^^^^^^^^^^^^-----⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
    d = datetime.strptime(input, "%Y-%m-%d %H.%M")  # parse to datetime object
    result = d.strftime("%m/%d/%Y %H:%M:%S")        # now convert to desired format
    #⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄-^^^^^^^^^^^^^^^^^ 
    '10/09/2018 20:00:00'