From c024a4c0999e595ed5c08c97b3c2334fa1d787e9 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 20 Mar 2015 14:38:18 +0800 Subject: [PATCH] use dateutil to parse string to datetime in python --- .../main/resources/python/swagger.mustache | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 5a5a7058bdf..23bafc6da64 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -194,10 +194,7 @@ class ApiClient: if objClass in [int, long, float, dict, list, str, bool]: return objClass(obj) elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], "%Y-%m-%dT%H:%M:%S.%f") + return self.__parse_string_to_datetime(obj) instance = objClass() @@ -214,7 +211,7 @@ class ApiClient: value = value setattr(instance, attr, value) elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], "%Y-%m-%dT%H:%M:%S.%f")) + setattr(instance, attr, self.__parse_string_to_datetime(value)) elif 'list[' in attrType: match = re.match('list\[(.*)\]', attrType) subClass = match.group(1) @@ -230,6 +227,17 @@ class ApiClient: return instance + def __parse_string_to_datetime(self, string): + """ + Parse datetime in string to datetime. + + The string should be in iso8601 datetime format. + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string class MethodRequest(urllib2.Request): def __init__(self, *args, **kwargs): @@ -243,4 +251,4 @@ class MethodRequest(urllib2.Request): return urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) \ No newline at end of file + return getattr(self, 'method', urllib2.Request.get_method(self))