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)
Related
I need to transform dates to this format:
#(Optional) Start date in format YYYY-MM-DD%20HH:NN:SS.
To make api call and then get from it date 7 days earlier
from datetime import datetime, timedelta
end = datetime.now().strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start )
print("End: ", end )
I tried to do it this way but I get an error
unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
Thanks to Peter Wood i fixed this silly mistake
end_time = datetime.now()
start_time = end_time - timedelta(days=7)
end = end_time.strftime("%Y-%m-%d%%20%H:%M:%S")
start = start_time.strftime("%Y-%m-%d%%20%H:%M:%S")
print("Start: ", start )
print("End: ", end )
With strftime you are casting end to string, remove that part like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start)
print("End: ", end)
If you want to format your output you can then add .strftime("%Y-%m-%d%%20%H:%M:%S") like this:
from datetime import datetime, timedelta
end = datetime.now()#.strftime("%Y-%m-%d%%20%H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start.strftime("%Y-%m-%d%%20%H:%M:%S"))
print("End: ", end.strftime("%Y-%m-%d%%20%H:%M:%S"))
from datetime import datetime, timedelta
from urllib.parse import quote
end = datetime.now()
start = end - timedelta(days=7)
print("Start: ", quote(start.strftime("%Y-%m-%d %H:%M:%S")))
# Start: 2022-09-27%2008%3A28%3A11
I want to compare todays time with another new time without hour/min or seconds. Ignore hour and minutes...
In other words if both days are the same no matter hours or minutes it is ok (Extra) otherwise it is not good (Too old)... I tried but even with the same day still continue to compare with hour/min and sec. How can I do it?
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")`
Compare using only the date component of datetime, accessible via the .date() attribute:
import datetime
currentdate = datetime.datetime.now()
print(currentdate)
newsdate = "Oct-26-2021"
newsdate = datetime.datetime.strptime(newsdate, "%b-%d-%Y")
print(newsdate)
if currentdate.date() == newsdate.date():
print("Extra")
else:
print("Too old")
The above can also be reworded as follows (perhaps to aid in readability for others):
from datetime import date, datetime
currentdate: date = date.today()
print(currentdate)
date_string = "Oct-26-2021"
newsdate: date = datetime.strptime(date_string, "%b-%d-%Y").date()
print(newsdate)
if currentdate == newsdate:
print("Extra")
else:
print("Too old")
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
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
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