Django: time data '2022-09-02 11:13 am' does not match format '%Y-%m-%d %H%M%S.%f'

Viewed 53

I want to implement scheduling functionality, and for that, I need to convert the DateTime format. I am trying to format DateTime in the views.py file. But I am getting this error while converting data to DateTime.

Here is my code.

FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").date()
FinalScheduleTime = datetime.datetime.strptime(scheduletime, "%Y-%m-%d %H%M%S.%f").strftime('%Y-%m-%d')

I have tried both ways to convert data but it is not working for me. I am new to python Django. Grateful for the help in advance.

2 Answers

When converting from datetime str containing AM/PM you should not use %H, instead use %I

import datetime

datetime_str_am = '2022-03-03 3:40 AM'
datetime_str_pm = '2022-03-03 3:40 PM'

am = datetime.datetime.strptime(datetime_str_am, '%Y-%m-%d %I:%M %p')
pm = datetime.datetime.strptime(datetime_str_pm, '%Y-%m-%d %I:%M %p')
Related