What is the datetime format for flask-restful parser?

TukeV picture TukeV · Oct 30, 2014 · Viewed 9.1k times · Source

Let's say that I have following parser inside my get method:

from flask.ext.restful import reqparse

parser = reqparse.RequestParser()
parser.add_argument('when', type=datetime, help='Input wasn\'t valid!')

And then I want to test the said get method with curl...

curl --data "when=[WHAT SHOULD I WRITE HERE?]" localhost:5000/myGet

So the question is, how I should call the get method? I've tried numerous different formats, tried to read rfc228 standard, etc. but I can't figure out the right format.

Answer

eyscode picture eyscode · Aug 4, 2016

Kinda late, but I've just been in the same problem, trying to parse a datetime with RequestParser, and sadly the docs are not so helpful for this scenario, so after seeing and testing RequestParser and Argument code, I think I found the problem:

When you use type=datetime in the add_argument method, under the hood it just calls datetime with the arg, like this: datetime(arg), so if your param is a string like this: 2016-07-12T23:13:3, the error will be an integer is required.

In my case, I wanted to parse a string with this format %Y-%m-%dT%H:%M:%S into a datetime object, so I thought to use something like type=datetime.strptime but as you know this method needs a format parameter, so I finally used this workaround:

parser.add_argument('date', type=lambda x: datetime.strptime(x,'%Y-%m-%dT%H:%M:%S'))

As you can see in this way you can use whatever format datetime you want. Also you can use partial functool instead of lambda to get the same result or a named function.

This workaround is in the docs.