How to store datetime with millisecond precision in SQL database

Question:

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?

Asked By: alphanumeric

||

Answers:

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
Answered By: LFLFM

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
Answered By: meshy

When using sqlalchemy with SQLite, the default DateTime column type doesn’t store fractional seconds. Instead, you have to use the SQLite dialect DATETIME type: https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#sqlalchemy.dialects.sqlite.DATETIME

Answered By: Marthinwurer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.