Jin Nii Sama
Jin Nii Sama

Reputation: 747

Django rest framework timefield input format

After hours of searching, I found many posts that are related but wasn't able to help.

What I want to do is input eg: 10:30 AM into the TimeField.
In the django rest framework API on the browser, it is using this 10:30 AM format ('%I:%M %p').
But when I am using postman to test it, the output is in 24hr format ('%H:%M:%S'). I also tried to use 10:30 PM as input but the output I get is 10:30:00 instead of 22:30:00.

Many of the answers I found suggest to change the TimeField format in settings.py by using this line:

TIME_INPUT_FORMATS = ('%I:%M %p',)

but it doesn't work for me.

Sorry for my inexperience on django rest framework as I am still learning.

Here is the screenshot of the result. On browser API:

On browser API

On postman:

On postman

Upvotes: 5

Views: 5558

Answers (2)

John Moutafis
John Moutafis

Reputation: 23144

If you check the documentation on the TimeField you will see:

Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None)

Where

format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python.

input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].

So you either can specify the format and input_formats on the serializer, or set the settings.TIME_FORMAT and settings.TIME_INPUT_FORMATS.

Let's set the first case:

class MySerializer(serializers.Serializer):
    ...
    birthTime=serializers.TimeField(format='%I:%M %p', input_formats='%I:%M %p')

Some suggestions:

  1. Make your variable names snake case: birth_time.
  2. You may need to play a bit around with the input format because you may expect many different inputs:

    input_formats=['%I:%M %p','%H:%M',...]
    

Upvotes: 8

Joble Jose
Joble Jose

Reputation: 1

Convert the result in Serializer validate method and return it.

import time
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )

Upvotes: -1

Related Questions