0

I am trying to convert a string to datetime object using the strptime function.

code

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
2
  • "does this only work with the given format or is it dynamic as per the user input?" It works as per the input. You just need to provide the right format specifiers Commented Oct 31, 2022 at 6:43
  • %Y for long year format (2022) in place of %y for short year format (22)... Commented Oct 31, 2022 at 7:52

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.