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
Rumi
  • 44
  • 5
  • "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 – Abirbhav G. Oct 31 '22 at 06:43
  • `%Y` for long year format (2022) in place of `%y` for short year format (22)... – D.L Oct 31 '22 at 07:52

1 Answers1

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')
Abirbhav G.
  • 369
  • 3
  • 14