python3 calculate minutes since last mysql data entry

37 views Asked by At

I have python3 program that writes to a mysql database and I want the python3 program to send an alarm if it has been more than 15 minute since the last entry. The problem is I don't know how to subtract the python3 datetime.now() from the mysql datetime table entry

Thanks

1

There are 1 answers

0
Shakeel On

I am bit unclear about the datetime stored in table, If you are storing datetime in proper format then just normal subtraction should work.

import datetime
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="dummyuser",    # Enter your username
  passwd="dummypass",  # Enter your password
  database="mydatebase"
)

mycursor = mydb.cursor()
mycursor.execute("SELECT date_time_column FROM mytable ORDER BY id DESC LIMIT 1;")
curr_date = datetime.datetime.now()
print("Current datetime Type:", type(curr_date))
print("Current datetime:", curr_date)


for x in mycursor:
    y = x[0]
    print("DB datetime Type", type(y))
    print("DB datetime", y)
    print("Difference between current time and DB time:", curr_date - y)

Output:

Current datetime Type: <class 'datetime.datetime'>
Current datetime: 2019-11-13 15:28:03.908454
DB datetime Type <class 'datetime.datetime'>
DB datetime 2019-10-27 15:07:04.378052
Difference between current time and DB time: 17 days, 0:20:59.530402