简体   繁体   English

peewee 日期时间字段到微秒

[英]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;我插入了一堆格式与2005-06-03 16:12:01.215908相同的数据,我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.我查了文档http://docs.peewee-orm.com/_/downloads/en/latest/pdf/ ,根据第167页顶部的信息,我不知道为什么格式没有按预期工作。

When you declare your MySQL schema you need to specify precision of 6:当您声明 MySQL 架构时,您需要指定精度为 6:

https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html 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:您应该能够创建一个 peewee 子类,将其指定为发出的 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.我对我的 MariaDB 10.4 安装进行了测试,它工作正常。


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. DateTimeField已经将您使用的格式定义为选项列表中的第一个格式。 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.因此,如果您将字符串指定为“开始”值,则它们已经被正确解析,而无需您指定任何格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM