Naftuli Kay
Naftuli Kay

Reputation: 91830

Convert string to datetime.time object

I'm persisting datetime.time objects in MongoDB using MongoEngine and am developing a field for this.

Converting a Python datetime.time object into a MongoDB representation is fairly easy (str(datetime.time(14, 30))), but how should I convert it back to a native Python type from a string? Is there a built-in method for doing so?

I'd like to avoid writing a regex for this if possible, but if that's the solution, that's the solution.

Upvotes: 2

Views: 1204

Answers (2)

clcto
clcto

Reputation: 9648

Isn't this the purpose of DateTimeField (references: Defining Documents and API Reference). I haven't worked with MongoEngine or worked with MongoDB in python, so I am not sure if I am missing something from my quick read of the documentation.

Is there any reason you are not using the MongoDB PyMongo and MongoClient? Their documentation states:

Note that documents can contain native Python types (like datetime.datetime instances) which will be automatically converted to and from the appropriate BSON types.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

Use datetime.strptime() to get a datetime, and then the time() method to get the time.

Upvotes: 3

Related Questions