pythondatetimetime

Converting string to datetime with strptime in Python


I'm trying to convert a string to datetime with dd/mm/YYYY format, but the function strptime seems isn't working properly. The result format isn't in the same that i am specifying in the function.

import datetime
from datetime import datetime
from datetime import date

today = date.today()
print (today)
today = today.strftime("%d-%m-%Y %H:%M:%S")
print (today)

today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)

My output is this:

2022-08-26
26-08-2022 00:00:00
2022-08-26 00:00:00

it seems that after the strftime function, the format is right, but when I call the strptime function, it's getting back to the previous format "YY-mm-dd"


Solution

  • today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
    print (today)
    

    That part is creating a datetime object. You can do:

    print (today.strftime("%d-%m-%Y %H:%M:%S"))
    

    again in the final line