The date and time format and it processing when parsing

The common format of date and time used in our project is ISO. Basically it has the next form:

ISO8601_FMT = Y-m-dTH:M:S.mmmmmm

Example: 2000-01-01T01:01:01.123456

The length of microseconds should be always defined specifically, like as in the example (6 digits)

If microseconds are equal to zero they should be anyway prescribed:

for example:


When parsing, for example in case GET query, you can use the next function to get date and time in format datetime and check that the format is correct:

def datetime_from_iso8601(datetime_str):
    return json.dumps(
        dateDeserialiser({DATE_FIELD: datetime_str}, DATE_FIELD),

Function aniso8601.parse_datetime(datetime_str) receives a date string which has ISO format. Next the function converts that string to datetime format. If the string has incorrect format, exception ValueError will be thrown.

Then obtained datetime object  is passed to the function dateSerialiser where date and time will be converted to a comprehensible for JSON string.

def dateSerialiser(obj):
    if isinstance(obj, datetime):
        return '{0}{1}'.format(obj.isoformat(), '' if obj.microsecond > 0 else '.000000')
    raise TypeError('Type is not datetime')

Example of using:

To extract the date from the JSON format is used the next function:

def dateDeserialiser(dict_with_date, param_date):
        if param_date in dict_with_date and dict_with_date[param_date] is not None:
            obj = dict_with_date[param_date].replace(''', "").replace('"', '')
            return datetime.strptime(obj, ISO8601_FMT_MILLS)
    except ValueError:
        print ISO_FORMAT_ERROR
    return None

This function receives the JSON dictionary which has the converted date object and time object and the key param_date that points on date object and time object to retrieving. Function datetime.strptime(datetime_str, datetime_format) converts a string with the date and time in the described format to datetime object.

Example of using:

ShareShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on VKEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *