Python: serializing/deserializing datetime.time

datetime, python

Solution

In Python 3.6 and newer you can use the `datetime.time.isoformat` function to serialize and in Python 3.7 and newer you can use the `datetime.time.fromisoformat` function to deserialize. So it would look like this

import datetime
time_string = datetime.datetime.now().time().isoformat()
time_obj = datetime.time.fromisoformat(time_string)

and to do this with a `datetime` instead of a `time`, it would look like

import datetime
datetime_string = datetime.datetime.now().isoformat()
datetime_obj = datetime.datetime.fromisoformat(datetime_string)

Problem

I have a form with dropdowns full of times, represented with datetime.time objects. What's the best way to serialize the object? eg: ``` <option value="${time.serialize()}">${time.isoformat()}</option> ``` And then deserialize it on the other end? eg: ``` time = datetime.time.deserialize(request.params['time']) ```

Original source