I am basically trying to compare a given set of datatime to a predefined threshold. End objective is to get rows in a column if it exceeds the threshold.
Here is the code what I have tried so far:
#!/usr/bin/python
from datetime import datetime
import sys
import logging
import operator
import pymysql
import pandas as pd
db_endpoint = "awsendpoint"
db_username="user"
db_password="password"
db_name="database_name"
port = 3306
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(db_endpoint, user=db_username,
passwd=db_password, db=db_name, connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
logger.info("SUCCESS: Connection to RDS mysql instance succeeded")
cur=conn.cursor()
cur.execute("select talendjobname, taskstartdate from taskexecutionhistory where basicstatus = 'RUNNING'")
#OUTPUT is :
[('Prod_Adobe_Master_Process_v2', datetime.datetime(2018, 12, 17, 3, 30)), ('Prod_Sales_n_DG_Master_Process_v2', datetime.datetime(2018, 12, 17, 4, 0)), ('SDG_download_mail_attachments', datetime.datetime(2018, 12, 23, 3, 0, 1))]
aws = []
for row in cur:
aws.append(row)
# All working upto this.
aws = pd.DataFrame(aws)
aws_time = aws.iloc[:,1]
## I am getting the longer running jobs with respect to current time.
def days_between(d1):
# d1 = datetime.strptime(d1, "%Y-%m-%d")
return abs((datetime.now() - d1))
#Here is the problem
OUTPUT is a list of : 3Days 11 hours 30 mins,
2Days 10 hours 12 mins,
so on and so forth
My threshold value is 8 Hours which I am not able to compare with this result. I wish to get the list of jobs which have only crossed this threshold.
Some additional things I have tried:
time_passed = []
for i in range(0,len(aws_time.index)):
x = days_between(aws_time[i])
time_passed.append(x)
Let me know what I am missing or if there is any different approach. TimeDelta is the major class I am struggling with. I tried to work on string operations but not able to convert the output as string also.
datetime.timedelta
objects in Python have a method called .total_seconds()
which you can use to find the hours between two times.
from datetime import datetime, timedelta
t1 = datetime.now()
t2 = datetime.now() - timedelta(hours=10)
type(t1 - t2)
datetime.timedelta
# Find total hours between times
(t1 - t2).total_seconds() / 3600
9.99999
You can vectorize your operations to find all of the time differences in hours at once (using .dt
to access the time differences):
# Find the time differences and convert to hours
aws['time_diff'] = aws.iloc[:, 1].apply(days_between)
aws['time_diff_hours'] = aws['time_diff'].dt.total_seconds() / 3600
And then subset to the rows with hours greater than 8
greater_than_8_hours = aws[aws['time_diff_hours'] > 8]