Skip to content Skip to sidebar Skip to footer

How To Get The Value Of A Datetimefield In Peewee

class Test(Model): time = DateTimeField() # ... row = Test.select()[0] test.time This returns a string that looks like this: 2017-01-23 01:01:39+01:00. How can I get it as a

Solution 1:

Are you using SQLite? If so, SQLite doesn't have a dedicated datetime type, so datetimes are stored as strings in the DB. What peewee will do is recognize certain datetime formats coming out of the DB and convert them to datetime objects. What you need to do is ensure that either:

  1. When you create/save your object, that you assign a datetime object to the field.
  2. When reading back pre-existing data, that the data is in a recognized format.

The formats peewee supports out-of-the-box for datetime field are:

  • YYYY-mm-dd HH:MM:SS.ffffff
  • YYYY-mm-dd HH:MM:SS
  • YYYY-mm-dd

It looks like your has zone info. I'd suggest converting to UTC and dropping the zone info. That should fix it.

Solution 2:

Have you tried adding a default like this?

time = DateTimeField(default=datetime.datetime.now())

Or when adding an entry add it as a datetime.datetime object directly:

test = Test(....., time=datetime.datetime.strptime("2018-3-15", '%Y-%m-%d'))

In the second case you don't need to specify anything in the class definition...

Post a Comment for "How To Get The Value Of A Datetimefield In Peewee"