Unable to find difference between two datetime variable - python

i am trying to find difference of two datetime variable in python
i tried using direct difference of two variables, tried using strptime() function
from datetime import datetime
time = datetime.now()
#timestamp variable gets time value from database
print "time 1:" + str(timestamp)
print "time 2:" + str(time)
#diff = timestamp-time; #already tried
#diff = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.strtime(time, "%Y-%m-%d %H:%M:%S") # already tried
diff= datetime.datetime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.datetime(time, "%Y-%m-%d %H:%M:%S")
print diff
Expect the output in seconds and actual result is type error

You can use total_seconds() on datetime.timedelta to get difference in seconds:
diff = (timestamp-time).total_seconds()
Code:
from datetime import datetime
timestamp = '2019-04-01 07:12:00'
time = '2019-04-01 07:11:0'
print("time 1:" + str(timestamp))
print("time 2:" + str(time))
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
diff = (timestamp-time).total_seconds()
print(diff)
# 60.0

Related

Calculating time intervals in Python, a more smarter way

was trying to calculate and a timedelta element with a str concatente, finally got it but feel there should be a smarter way to do this, any idea pls. here are my lines of code:
import datetime
import time
currentTime = datetime.datetime.now()
print("The time now is " + currentTime.strftime('%I:%M %p'))
realTime = currentTime.strftime('%I:%M:%S %p')
realTime was necessary to convert the datetime currentTime to a str to feed to strptime
print(realTime)
meetTime = input("Please input the meeting time in 12hrs timing")
# timeToMeet = datetime.datetime.strptime('11:50PM', '%I:%M%p').time()
timeToMeet = datetime.datetime.strptime(meetTime, '%I:%M%p')
tried both static and input time and they both worked
print(timeToMeet.strftime('%H:%M %p'))
timeNow = datetime.datetime.strptime(realTime, '%I:%M:%S %p')
print("The time now is " + timeNow.strftime('%I:%M%p'))
tdelta = timeToMeet - timeNow
print("Please, your meeting starts in " + str(tdelta))
print(tdelta)

Different between two times with if function

I will compare a dataset server time and the actual time. If the different greater than 1 minute, the script is continued. Else a waiting loop for example 10 sec. will start.
But I can't execute the if function. Thanks for your help!
That's the output:
last importtime: 2019-07-05 14:16:07
actual time: 2019-07-05 18:30:21
1 day, 4:14:14
Error:
TypeError: '>' not supported between instances of 'datetime.timedelta' and 'datetime.datetime'
Code:
from datetime import datetime
import mysql.connector
import pandas as pd
#db-connection#
mydb = mysql.connector.connect(host="localhost",port="xx",user="xx",passwd="xxx",database="traiding")
mycursor = mydb.cursor()
mycursor.execute("select max(imported) from import_log")
data_sql=mycursor.fetchall()
#last import from database'
data=pd.DataFrame(data_sql, columns=['date'])
#close connection#
mycursor.close()
mydb.close()
#last import date#
lastimported=datetime.strftime(data_sql[0][0], "%Y-%m-%d %H:%M:%S")
print("last importtime:",lastimported)
#lastimport=datetime.strptime(lastimported, "%Y-%m-%d %H:%M:%S")
current_time=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
print ("actual time: ", current_time)
s1 = lastimported
s2 = current_time
FMT = '%Y-%m-%d %H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print (tdelta)
min_time=datetime.strptime('00:01:00', "%H:%M:%S")
if tdelta > min_time :
print (">0") # Do Something
else:
print ("else") # Waiting loop, for example 10sec
You have to compare the timedelta object to another timedelta object.
import datetime as dt
#... Your code
if tdelta > dt.timedelta(minutes=1):
print (">0") # Do Something
else:
print ("else") # Waiting loop, for example 10sec

Joining 2 time strings

I am trying to solve a problem. where I am defining date and time as string in below mentioned format.
date1 = '2016-12-1'
time1 = '10:30 AM'
time2 = '11:30 PM'
I have another string add_time = '01:50' type of variables is string.
what I'm looking for is:
new_date_and_time = time1 + add_time
so that it returns
date1 and new_date_and_time
> 2016-12-1, 12:20 PM (10:30 AM + 1:50)
but if I am adding time2 + add_time the date is also changed,
so it should print 2016-12-2, 1:20 AM
Is there any package which can do this?
Convert strings to datetime object, then add time using timedelta
from datetime import datetime, timedelta
date1 = '2016-12-1'
time1 = '10:30 AM'
date_object = datetime.strptime(date1 + ' ' + time1, '%Y-%m-%d %I:%M %p')
new_date_object = date_object + timedelta(hours=1) + timedelta(minutes=50)

Adding x seconds worth of time onto a string variable time of HH:MM

I'm trying to work out a way to make a new variable AUTOMATIC_END_TIME based on adding the minimum amount of time onto the start time but I can't figure out the way to allow START_TIME to be turned into a time that can then have time added onto it.
So far my script has the following:
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = "" # Should come out as 19:30
The current script shouldn't change at all except for AUTOMATIC_END_TIME which should be START_TIME + (60 * (5 + 1) It should come out as 19:30
>>> (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
'19:30'
from time import sleep
from datetime import datetime, timedelta
START_TIME = "19:18"
END_TIME = "19:25"
LOGA = ["one", "two"]
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds
if len(LOGA) * (60 * (5 + 1)) >= TIME_DIFFERENCE:
print "Show minimum end time"
AUTOMATIC_END_TIME = (datetime.strptime(START_TIME, "%H:%M") + timedelta(minutes=12)).strftime('%H:%M')
print AUTOMATIC_END_TIME

how to convert string to datetime.timedelta()?

how can i convert my string of date to a datetime.timedelta() in Python?
I have this code :
import datetime
date_select = '2011-12-1'
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
thanks in advance ...
You wouldn't convert date_select to a timedelta, instead, you need a datetime object, which can be added to a timedelta to produce an updated datetime object:
from datetime import datetime, timedelta
date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
Or, if you prefer, without the fancy from ... import ... import line:
import datetime # <- LOOK HERE, same as in your example
date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
You use strptime to do this.
from datetime import datetime
target_date = datetime.strptime(date_select, '%Y-%m-%d')
from datetime import datetime, timedelta
date_select = '2011-12-1'
new_data = datetime.strptime(date_select, '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
You will get 2011-12-02 00:00:00; to strip off the '00:00:00' and get only the date, just add .date() to target_date
print target_date.date()
This should give you the only the date = 2011-12-02

Categories