Search code examples
pythondatetimepeewee

I want to store datetime in peewee.DateTimeField(), I use datetime.datetime.now() in that field as default but it can't work


this code cannot work and give json serializable error

  class Bank(peewee.Model): // create Bank table
        bank_id     = peewee.PrimaryKeyField()
        bank_name   = peewee.CharField()
        account_no  = peewee.CharField()
        ifc_code    = peewee.CharField()
        swift_code  = peewee.CharField(null = True)
        modify_date = peewee.DateTimeField(default=datetime.datetime.now(),formats=['%Y-%m-%d'])/*date in yyyy-mm-dd formate*/
        status      = peewee.IntegerField(default = 0)

        class Meta:
            database = db

Solution

  • This answer is very incorrect - please see my answer below (@coleifer).


    The default date that you are providing is not a datetime object. Rather it's a string!

    modify_date = peewee.DateTimeField(default=datetime.datetime.now().strftime('%Y-%m-%d'))
    

    type(datetime.datetime.now().strftime('%Y-%m-%d')) --> str

    You can pass default current datetime object like this:

    date = datetime.datetime.now().strftime('%Y-%m-%d')
    need_date = datetime.strptime(date, '%Y-%m-%d')
    
    modify_date = peewee.DateTimeField(default=need_date)
    

    or

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