Search code examples
pythonpeewee

peewee datetime field to microsecond


I define my data field as

class test(BaseModel):
    start = DateTimeField(formats='%Y-%m-%d %H:%M:%S.%f')

and I insert a bunch of data with format same with 2005-06-03 16:12:01.215908, I check the table with select start from test;

+---------------------+
| start               |
+---------------------+
| 2005-06-05 01:17:45 |
| 2005-06-05 00:47:47 |
| 2005-06-03 16:12:01 |
| ...                 |

I looked up the document http://docs.peewee-orm.com/_/downloads/en/latest/pdf/, according to the info on the top of page 167, I don't know why the format didn't work as expected.


Solution

  • When you declare your MySQL schema you need to specify precision of 6:

    https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

    You should be able to create a peewee subclass that specifies this as part of the emitted DDL:

    class MyDateTimeField(DateTimeField):
        def get_modifiers(self):
            return [6]
    
    ...
    start = MyDateTimeField()
    

    I tested this against my MariaDB 10.4 install and it is working correctly.


    Formats needs to be a list, first of all. As you have it written, it will execute one character at-a-time, which is definitely not what you want.

    The DateTimeField already defines the format you are using as the very first format in the list of options. So if you are specifying strings as your "start" value, they will already be correctly parsed without your having to specify any formats at all.