set input to AM PM in django timefield
Asked Answered
T

4

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?

Tanah answered 4/11, 2014 at 17:21 Comment(0)
J
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

Jewelry answered 14/6, 2017 at 16:3 Comment(2)
Really useful and DRY.Actress
By this method, we are still not able to use AM or PM in input field and we have to use 24-hour clock to provide the input though AM or PM is stored in the database.Bath
H
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.

Hatbox answered 20/6, 2015 at 16:54 Comment(0)
C
1

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

field = DateTimeField(input_formats='%H:%M %p',...)
Company answered 4/11, 2014 at 17:40 Comment(1)
The time now shows up as 14:30:00 for me. Is this format correct?Tanah
C
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',)
Crash answered 4/11, 2014 at 17:39 Comment(3)
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?Tanah
I'm a bit late with this comment but there is no such thing as 14:30 AM to begin with.Heavierthanair
This answer worked for me except instead of %H, change it to %I. Like so: TIME_INPUT_FORMATS = ( '%I:%M %p', )Diclinous

© 2022 - 2024 — McMap. All rights reserved.