peewee 日期时间字段到微秒

peewee datetime field to microsecond

我将我的数据字段定义为

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

然后我插入了一堆格式与2005-06-03 16:12:01.215908相同的数据,我用select start from test;

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

我查阅了文档http://docs.peewee-orm.com/_/downloads/en/latest/pdf/,根据第167页顶部的信息,我不知道为什么格式没有按预期工作。

当您声明 MySQL 架构时,您需要指定精度为 6:

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

您应该能够创建一个 peewee 子类,将其指定为发出的 DDL 的一部分:

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

...
start = MyDateTimeField()

我针对我的 MariaDB 10.4 安装进行了测试,它运行正常。


首先,格式需要是一个列表。正如你写的那样,它会执行一个字符at-a-time,这肯定不是你想要的。

DateTimeField已经将您正在使用的格式定义为选项列表中的第一个格式。因此,如果您将字符串指定为“起始”值,则无需指定任何格式即可正确解析它们。