I am trying to figure out how to accept am/pm as a time format in Django using a DateTime field, but I am having some trouble. I have tried setting it like this in my forms.py file
pickup_date_time_from = DateTimeField(input_formats=["%m/%d/%Y %I:%M %p"])
with the following data:
12/31/2017 02:40 pm
However, I get a validation error when submitting the form:
(Hidden field pickup_date_time_from) Enter a valid date/time.
I have also tried setting a global variable in settings.py as the documentation states:
DATETIME_INPUT_FORMATS = ['%m/%d/%y %I:%M %p']
What does work is if I submit the data without the am/pm, but the output is
2017-12-31 02:40:00+00:00
Any other options?
DATETIME_INPUT_FORMATS doesn't work for formats containg %p.
Neither do input_formats
kwarg.
As a quick work around, you can alter the input_formats
attribute of DateTimeField
in the Form
's __init__
method.
For example:
class DateTimeForm(forms.Form):
CUSTOM_FORMAT = '%m/%d/%y %I:%M %p'
date_input = forms.DateTimeField(widget=forms.HiddenInput)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.CUSTOM_FORMAT not in self.fields['date_input'].input_formats:
self.fields['date_input'].input_formats.append(self.CUSTOM_FORMAT)
Django documentation does say that %p cannot be used in parsing date fields.
But if you go through the source code, the to_python method of DateTimeField doesn't really enforce anything like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With