6

i want to allow users to be able to choose between am and pm with my django timefield

Currently if I enter:

11:00 AM

, i get a form error: "Enter a valid time."

If I enter:

11:00

the form validates with no problem.

I also tried:

class RemindersForm(forms.ModelForm):

    remdinder = forms.TimeField(input_formats='%H:%M %p',)

    class Meta:
        model = NotificationPreference
        fields = (
                  'reminder', 
                  )

This changes the input format to:

11:00:00

and still gives me the above validation error.

What am I doing wrong?

Atma
  • 29,141
  • 56
  • 198
  • 299

4 Answers4

14

I was searching for a similar answer and I didn't find a suitable one for models.TimeField, so, the easiest solution that I found for doing this site wide would be to setting in your settings.py the following global variable:

TIME_INPUT_FORMATS = ['%I:%M %p',]

I hope this helps someone.

To use other formats see:

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

LostMyGlasses
  • 3,074
  • 20
  • 28
virsunen
  • 494
  • 5
  • 8
10

To get a 12hr time format you would use the following:

For input (This is the list of formats Django uses in validation):

field = TimeField(input_formats=('%I:%M %p',...,...))

For output (This is the format Django will use to display time values):

field = TimeField(widget=TimeInput(format='%I:%M %p'))

The %I indicates a 12 hour clock format whereas the %H indicates a 24 hour clock format.

Additionally, the default list of input_formats can be found in each locales formats.py file. Django uses the first format in the input_formats list as the default output format for time fields.

smarlowucf
  • 311
  • 3
  • 11
1

I think you can do some thing like this in forms.py

field = DateTimeField(input_formats='%H:%M %p',...)
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
0

According to the Django documentation, and python's datetime docs, it should work if you change the time input settings to:

TIME_INPUT_FORMATS = ('%I:%M %p',)
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
schneck
  • 10,556
  • 11
  • 49
  • 74
  • Are you saying to add this to the form field constructor? Also, this time format shows up as 14:30:00 for me. Is this format correct? – Atma Nov 04 '14 at 18:24
  • I'm a bit late with this comment but there is no such thing as 14:30 AM to begin with. – Erik Lumme Aug 28 '16 at 17:29
  • This answer worked for me except instead of `%H`, change it to `%I`. Like so: `TIME_INPUT_FORMATS = ( '%I:%M %p', )` – Lewis Menelaws Apr 03 '18 at 02:23