简体   繁体   中英

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

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.

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM