Home > Back-end >  Converting string to datetime with strptime in Python
Converting string to datetime with strptime in Python

Time:08-27

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, its getting back to the previous format "YY-mm-dd"

CodePudding user response:

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

CodePudding user response:

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

That is because print(today) determines the format since you didn't specify one. As other's pointed out, today is a datetime object. When you print() a datetime object, python will choose a format for you, I assume based on your system's locale settings.

One concept to understand here is the difference between a value and the representation of that value as a string. This is what formatting a datetime is for.

I suggest you don't worry about the output here too much. As long as your explicit format with strftime() gives you the correct representation, then you are good. This formatting should only be used for output. Otherwise, store datetimes and datetime objects in your variables.

  • Related