Using Rouble's suggestion and Maulik Gangani's example based on that suggestion:
How do I determine if current time is within a specified range using Python's datetime module?
I have two time strings that have been converted into a datetime object using .strptime as follows:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
I have a datetime object for time now:
timeNow = datetime.now()
My problem is that unless I convert timeNow (datetime object) into a string and then back again using .strptime , the script will not work:
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
Full code:
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M')
timeStart = datetime.strptime(timeStart, '%H%M')
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
My question is, how do I format timeNow = datetime.now() so that I can compare it against a string in 24hr format '0000' without having to convert datetime.now() to a string and back again?
The reason why your code is not working, it's because apart from time, datetime (as the name suggests) holds also information about the date.
When you run the following code:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
The hour and minute is converted, but the rest (the "date" part) is assumed to be epoch:
repr(timeStart)
# Output: 'datetime.datetime(1900, 1, 1, 3, 0)'
When you run datetime.now(), however, that always assumes the current time + date:
>>> datetime.now()
datetime.datetime(2020, 7, 17, 8, 25, 18, 270848)
The reason why converting to string, and back from string works, is because when you convert your datetime to a string with the format '%H%M, you lose the date part in the resulting string. Converting back from that, there's only hour and minutes to read, so you're losing the date part.
Effectivelly, you should be using datetime.time, instead of datetime.datetime to compare time.
After reading using strptime, try using the .time() method to only extract the time part and lose the date part:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M').time()
And same for the timeNow part:
timeNow = datetime.now().time()
If you call datetime.strptime, a default date is added if you only supply a time string. datetime.now() will have today's date. You can remove that by using only the time part of the datetime object - which you get by calling the time() method, e.g.
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M').time()
timeStart = datetime.strptime(timeStart, '%H%M').time()
timeNow = datetime.now().time()
print(isNowInTimePeriod(timeStart, timeEnd, timeNow))
# True (my current time is 0823)
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)
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
SOAP client return seconds to end event.
How can I get from this seconds date in format "yyy-mm-dd hh:ii:ss"
A quick example (add 50000 seconds from now with datetime.timedelta):
>>> import datetime
>>> time_now = datetime.datetime.now()
>>> time_event = time_now + datetime.timedelta(seconds=50000)
>>> time_event.strftime("%Y-%m-%d %H:%M:%S")
'2010-05-08 12:07:05'