13

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

2 Answers 2

11

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()
Sign up to request clarification or add additional context in comments.

Comments

8

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.