Search code examples
pythonmysqlpymysql

How can I write a query that uses the current system time in PyMySQL?


I'm trying to write a SQL statement in Python that will use the current system time to query the database.

My database has a date field that is of type date so I thought a date object would work for the comparison but that doesn't seem to be true.

My statement currently looks like this:

current_time = datetime.datetime.now()
sql = "SELECT * FROM `table` WHERE `date`=current_time

However that's failing and telling me that my SQL is incorrect. I'm not sure if the problem is with SQL, Python or both but I haven't been able to find any examples online and I'm at the end of my rope.


Solution

  • Maybe it would be better using db servers time? If they are on single machine, there won't be difference in time, but you will avoid timezone and other problems.

    sql = "SELECT * FROM `table` WHERE `date`=curdate()";
    

    If you have to use Python's machine time, use .strftime("%d/%m/%y")

    Also, look for the correct format match in date field!