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.
CodePudding user response:
you take wrong format for am/pm
>>> from django.utils.dateformat.datetime import datetime
>>> datetime.now().strftime("%Y-%m-%d %H:%M %p")
'2022-09-02 08:04 AM'
>>> datetime.now().strftime("%Y-%m-%d %H:%M %p").lower()
'2022-09-02 08:04 am'
more here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
CodePudding user response:
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')