Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Losing microseconds when inserting date to database

I have this code snippet in a view:

time_from = datetime.strptime(req.POST['time_from'], "%Y-%m-%d %H:%M:%S.%f")

with connections["mssql_database"].cursor() as cursor:
                sql_statement = "EXEC SaveActivity @TimeFrom='%s'" % (time_from)
                print(sql_statement)
                cursor.execute(sql_statement)

It prints this SQL statement:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EXEC SaveActivity @TimeFrom='2021-12-01 08:34:54'

Microseconds are missing. They are zeros, but I need them in a database. How can I correct this?

>Solution :

Don’t perform string formatting. Pass the data as parameter. By using string formatting, it will use the str(…), which is for a datetime not very precise. Use:

with connections["mssql_database"].cursor() as cursor:
    sql_statement = "EXEC SaveActivity @TimeFrom='%s'"
    cursor.execute(sql_statement, (time_from,))

Using parameters over string interpolation is not only better to prevent data loss, it also prevents SQL injection where one might pass, for example through a string, an SQL query that will then modify or leak the database.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading