I have the following string 20211208_104755, representing date_time format. I want to convert it to the python datetime format using datetime.strip() method.
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%y/%m/%d')
However I am getting the following error.
ValueError: time data '20211208' does not match format '%y/%m/%d'
CodePudding user response:
The second argument in strptime has to match the pattern of your datetime string. You can find the patterns and their meaning on https://docs.python.org/3/library/datetime.html
In your case, you can format it as
from datetime import datetime
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print(datetime_object)
>>> 2021-12-08 10:47:55
CodePudding user response:
what should work is to define how the mydatetime
string is composed.
example:
%Y is the year (4 digits);
check here for format (section strftime() Date Format Codes)
So in your example I would assume it's like this:
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print (datetime_object)
result
2021-12-08 10:47:55
and
type(datetime_object)
datetime.datetime