How to store datetime with millisecond precision in SQL database

时间秒杀一切 提交于 2021-01-27 05:34:34

问题


With a float value representing date and time with millisecond precision:

import datetime
float_time = 1485538757.29289
print datetime.datetime.fromtimestamp(float_time) 

prints:

2017-01-27 09:39:17.292890

To store it in db:

from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'mytable'
    time_created = Column(DateTime, nullable=False)

But saved value is rounded down to 2017-01-27 09:39:17 (from 2017-01-27 09:39:17.292890). Is there is a solution?


回答1:


It depends on the SQL database you're using. They differ in precision:

PostgreSQL: Default 1 microsecond. (See docs for far-future/past caveats.)

MySQL: Default 1 second. Millisecond / microsecond precision optional after version 5.6.4.

MariaDB: Default 1 second. Millisecond / microsecond precision optional since version 5.3.

Transact-SQL (Microsoft SQL): Rounded to increments of .000, .003, or .007 seconds

SQLite: Datetimes can be stored as strings with arbitrary precision, but "only the first three digits are significant".

Oracle: Default 1 microsecond. Optional precision to 1 nanosecond.

Note:

  • Millisecond: 0.001s
  • Microsecond: 0.000001s
  • Nanosecond: 0.000000001s



回答2:


The most important piece of information is the one you missed in the original post: which database? Since you later mentioned that it's MariaDB, here you go:

Source: https://mariadb.com/kb/en/mariadb/microseconds-in-mariadb/

Since MariaDB 5.3, the TIME, DATETIME, and TIMESTAMP types, along with the temporal functions, CAST and dynamic columns, have supported microseconds. The datetime precision of a column can be specified when creating the table with CREATE TABLE, for example:

CREATE TABLE example(   col_microsec DATETIME(6),   col_millisec TIME(3) );

Generally, the precision can be specified for any TIME, DATETIME, or TIMESTAMP column, in parentheses, after the type name. The datetime precision specifies number of digits after the decimal dot and can be any integer number from 0 to 6. If no precision is specified it is assumed to be 0, for backward compatibility reasons.

Another example:

SELECT CAST('2009-12-31 23:59:59.998877' as DATETIME(3));
-> 2009-12-31 23:59:59.998


来源:https://stackoverflow.com/questions/41900415/how-to-store-datetime-with-millisecond-precision-in-sql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!