# Calculate time between time in python and time in mysql database

## Calculate time between time in python and time in mysql database

Contents

Problem Description:

`

``````import datetime
now = datetime.datetime.now ()
tgl = now.strftime("%Y-%m-%d")
y = now.strftime ('%H:%M:%S')
print(y)
>>> 20:01:10

crsr.execute("SELECT * FROM tblsolar WHERE tanggal LIKE '%s' AND id LIKE '1001' ;" % (tgl))
res = crsr.fetchall()
for i in res:
z = i
print(z)
>>>  8:09:34
``````
``````can someone help me in this situation
i want to calculate between z and y (time duration)
x = y - z
``````

any help thank you..

i have try
`

``````import datetime as dt
start_dt = dt.datetime.strptime(x, '%H:%M:%S')
end_dt = dt.datetime.strptime(y, '%H:%M:%S')
diff = (end_dt - start_dt)
print(diff)
``````

strptime() argument 1 must be str, not datetime.timedelta`

## Solution – 1

I reckon that the `%s` placeholder should appear alone and outside single quotes:

``````sql = "SELECT * FROM tblsolar WHERE tanggal = %s AND id = '1001'"
crsr.execute(sql, (tgl,))
res = crsr.fetchall()
``````

## Solution – 2

you mean this SQL Syntax?

``````SELECT FORMAT(GETDATE(), 'HH:mm:ss') as DT
``````

This should give you the same as the python time with format ‘%H%M%S’

## Solution – 3

ok i got the answer 🙂

``````    import datetime as dt
start_dt = x
end_dt = dt.datetime.strptime(y, '%H:%M:%S')
diff = (end_dt - start_dt)
print(diff.strftime("%H:%M:%S"))
``````

thank @Tim Biegeleisen for correction the code
thank NicoDorn for the input

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.