How to convert the string to date time format?

Question:

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'
Asked By: Lakpa Tamang

||

Answers:

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
Answered By: Gilian

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
Answered By: adhg
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.