Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
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:

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!