I have a small REST API with Python and Flask, and for some GET requests I need to accept a look-behind time duration parameter, e.g. "A months, B days, C hours, D minutes".
This parameter will be parsed from a query string, but I'm a bit unsure how I should be structuring my query string for parsing. There are other fields in the query string besides the look-behind, which complicates things a bit.
There are two main options I have come up with.
Accept a single field for the look-behind in the query string, e.g.
"8months5days"
, then extend some regex solution like virhilo's here for the string passed:regex = re.compile(r'((?P<hours>\d+?)hr)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?')
after which I can construct a
datetime.timedelta
from the result.Accept several fields for different components of a time duration in my query string, e.g.
"behind_m=8&behind_d=5"
. Then useurllib
to get a dictionary of the full query string,query_d = parse_qs(request.query_string)
and finally take the intersection of
query_d
with a dictionary likedurations = {'behind_m': 'months', 'behind_d': 'days', 'behind_y': 'years', ...}
after which I can directly construct a
datetime.timedelta
.
My natural inclination is to go for the second option, since I am weak with regex and I like the clarity. However, I could end up requiring multiple time durations in some query strings, which will result in enormously long query strings in some cases.
Is there a good way to accomplish this, and is that way regex? I understand that the entire task would be much simpler if there was a clean way to parse a time duration from some string format, but despite looking at datetime
and dateutil
I haven't found any support for duration parsing.