2

I'm currently trying to teach myself Django and I'm a little confused on how to modify data from a web API.

For example I request an api with a url:

api.example.com/events?location=....

And I get JSON data

{'data':
  [
    {
       'name': 'blah'
       'date': '2019-03-22'
    },
    {
       'name': 'blah2'
       'date': '2019-03-23'
    },
  ]
}

The date is outputted as "yyyy-mm-dd" and I want to change it to "mm dd yyyy". Would I have to put the JSON data into a model? If so, how would I go about doing so?

aw___
  • 23
  • 2
  • 1
    https://stackoverflow.com/questions/7737146/how-to-change-the-default-django-date-template-format – p14z Mar 22 '19 at 22:17
  • Would this work in my scenario? Date isn't in a model for it to know it is an datetime object. – aw___ Mar 22 '19 at 22:27
  • Is the JSON data generated by your django app or an external website? If the data is from an external website you can change DATE_INPUT_FORMAT in the settings: https://docs.djangoproject.com/en/dev/ref/settings/#date-input-formats – p14z Mar 22 '19 at 22:31

1 Answers1

1

I've the same problem I do this simply convert String to a new datetime object.

from datetime import datetime

def create_date(year, month, day):
    """
    Converts a Json Object Date to Datetime object
    :param year:
    :param month:
    :param day:
    :return:
        Date
    """
    if not isinstance(year, int):
        raise TypeError('year is not int')

    if not isinstance(month, int):
        raise TypeError('month is not int')

    if not isinstance(day, int):
        raise TypeError('day is not int')

    date_value = "{year}-{month}-{day}".format(year=year,
                                            month=month,
                                            day=day)

    return datetime.strptime(date_value, '%Y-%m-%d')
Eddwin Paz
  • 2,842
  • 4
  • 28
  • 48