I have a string from a pdf that I want to transform it to the date format that I want to work with later,
the string is 05Dec22
how can I change it to 12/05/2022?
import datetime date1 = '05Dec22' date1 = datetime.datetime.strptime(date1, '%d%m%Y').strftime('%m/%d/%y') date1 = str(date1)
This is what i tried so far
Advertisement
Answer
If you execute the code you’ll get the following error,
ValueError: time data '05Dec22' does not match format '%d%m%Y'
this is because your time string is not in the specified format given (‘%d%m%Y’). You can search for tables on the internet which show the placeholders that represent a certain formatting, if you look at the one provided here, you’ll see that the formatting your string has is ‘%d%b%y’, in this case, the %b placeholder represents the abbreviated month name and the %y placeholder is the year without century, just as your example string. Now, if you fix that in your code,
import datetime date1 = '05Dec22' date1 = datetime.datetime.strptime(date1, '%d%b%y').strftime('%m/%d/%Y') date1 = str(date1)
you’ll get the desired result. Note that you also have to change the output format in strftime. As I said before, the %y placeholder is the year without century. For you to get the year including the century, you have to use %Y.