Theron Luhn
Theron Luhn

Reputation: 4082

Python: serializing/deserializing datetime.time

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'])

Upvotes: 13

Views: 9517

Answers (2)

gene_wood
gene_wood

Reputation: 2073

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)

Upvotes: 7

agf
agf

Reputation: 176820

If you repr a datetime.time object, Python gives you isoformat. As reprs attempt to be serialized versions of their objects, that's a good indication it's the value you should use.

import datetime

timestring = datetime.datetime.now().time().isoformat()

timeobj = datetime.datetime.strptime(timestring, "%H:%M:%S.%f").time()

Upvotes: 11

Related Questions