I am trying to convert a string to datetime object using the strptime function.
I am encountering a ValueError that says format doesn't match, so I did double checking and confirmed that the format in the string matches the format I am passing as the parameter for strptime.
I have also referenced this question: time data does not match format but there the month and year were swapped.
So does this only work with the '%y-%m-%d %H:%M:%S' format or is it dynamic as per the user input like in my case '%y-%m-%d-%H:%M:%S' ?
input:-
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%y-%m-%d-%H:%M:%S')
output
ValueError: time data '2022-09-31-01:17:46' does not match format '%y-%m-%d-%H:%M:%S'
Expected output:
#while printing 'do'
2020-09-31-01:17:46
CodePudding user response:
You're almost there. You need %Y
instead of %y
since you're providing the year with the century (2022 instead of 22).
Your code would be
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%Y-%m-%d-%H:%M:%S')