I have a variable with the operating time of a store:
t = '08:00-17:00'
Now, i need to check if the store is open now:
from time import gmtime, strftime
print strftime("%H:%M", gmtime())
#11:26
What is the most adequate way to make this? As side note, i can have t in minutes, or something more convenient.
Instead of trying to convert the current time into string, you should rather str.split() the t into two different times, and then convert them into datetime.datetime.time objects using datetime.datetime.strptime() , and then compare that with the time component on datetime.datetime.now() . Example -
import datetime
t = '08:00-17:00'
times = t.split('-')
start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
if start_time <= datetime.datetime.now().time() <= end_time:
#Do you logic
Demo -
Closed time -
>>> import datetime
>>> t = '08:00-17:00'
>>> times = t.split('-')
>>> start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
>>> end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
>>> if start_time <= datetime.datetime.now().time() < end_time:
... print("Shop open")
...
>>>
Open time -
>>> t = '08:00-18:00'
>>> times = t.split('-')
>>> start_time = datetime.datetime.strptime(times[0],'%H:%M').time()
>>> end_time = datetime.datetime.strptime(times[1],'%H:%M').time()
>>> if start_time <= datetime.datetime.now().time() < end_time:
... print("Shop open")
...
Shop open
>>>
With this method even minutes are supported, you can change the format used to convert the time to a time object and support upto microseconds if you so wish.
First, you need to convert the t to a comparable value, such as a integer, so:
storeOpen, storeCloses = '08h00-17h00'.split('-')
This will split the string '08h00-17h00' into:
storeOpen => '08h00'
storeCloses => '17h00'
After that, you should transform the storeOpen and storeCloses into integer:
storeOpenHour, storeOpenMinutes = storeOpen.split('h') #splits the storeOpen into two
#converts to integer
storeOpenHour = int(storeOpenHour)
storeOpenMinutes = int(storeOpenMinutes)
#you should repeat the same process to storeClose
And then you just compare them:
if (nowMinutes > storeOpenMinutes and nowHour > storeOpenHour) and (nowMinutes < storeCloseMinutes and nowHour < storeCloseHour):
println "is open!"
Related
I want to measure the time difference between two time readings in a Python script.
time_stamp_1 = datetime.datetime.now()
# some task
time_stamp_2 = datetime.datetime.now()
time_stamp = time_stamp_2 - time_stamp_1
time_stamp_sec = ??
I got the result as 0:00:04.052000.
What exactly is this time format I am getting?
How to extract the time in seconds from time_stamp?
How to store time_stamp in an array like variable (as I want to use a loop and store the time_stamp for each loop)
How to store time_stamp_sec in an array like variable
1) It's a datetime.timedelta object which is being printed nicely:
>>> import datetime
>>> datetime.timedelta(days=3)
datetime.timedelta(3)
>>> print(datetime.timedelta(days=3))
3 days, 0:00:00
>>> print(datetime.timedelta(hours=3))
3:00:00
2) You can use total_seconds():
>>> t = datetime.timedelta(hours=3)
>>> t.total_seconds()
10800.0
This gives you a float as the datetime.timedelta may represent an amount of time which isn't an exact number of seconds.
3) You can append it to a list at each step in the loop:
>>> d = []
>>> d.append(t)
>>> d
[datetime.timedelta(0, 10800)]
4) You can do the same with the result of total_seconds():
>>> e = []
>>> e.append(t.total_seconds())
>>> e
[10800.0]
I have created a program which requires the user to input a given TimeType (Seconds/Minutes) and an objectivetime (integer) (e.g. if the user inputs Seconds and then 5, then the objective time is 5 Secs). In addition, the program also checks the time at the start and then checks the time after to work out the elapsed_time. I then wanted to check if the elapsed_time is more than or equal to the objective time. The code i have written is shown below (minus the other irrelevant code in between a and b)
import time, sys, os, random
a = datetime.datetime.now().replace(microsecond=0)
#random code...
b = datetime.datetime.now().replace(microsecond=0)
timetype = input("Enter time type: ")#Either Seconds or Minutes
objectivetime = input("Enter objective time: ")#This will be an integer
if timetype == 'Seconds':
#convert objectivetime to seconds and present in same format as a or b
else:
#convert objectivetime into minutes and present in same format as a or b
elapsed_time = b-a
if objectivetime<=elapsed_time:
'Well done'
else:
'You have exceeded the objective time'
Is there any way that the code could be edited to get the objective time to be formatted in the same way as a and b (start_time and end_time)??
Update--------------------------------------------------------------------------
How would I work out which time is bigger (elapsed_time or objtime)??
See updated code:
import time, sys, os, random
import datetime
a = datetime.datetime.now().replace(microsecond=0)
print(a)
#random code...
time.sleep(3)
b = datetime.datetime.now().replace(microsecond=0)
timetype = input("Enter time type: ")#Either Seconds or Minutes
objectivetime = input("Enter objective time: ")#This will be an integer
objectivetime = int(objectivetime) # I noticed you didn't do this in your code
delta = None
if timetype == 'Seconds':
delta = datetime.timedelta(seconds = objectivetime)
else:
delta = datetime.timedelta(minutes = objectivetime)
objtime = a + delta
print(objtime)
#How would I work out which time is greater?? (elapsed_time or objtime)
elapsed_time = b-a
print(elapsed_time-objtime)
objectivetime = int(objectivetime) # I noticed you didn't do this in your code
delta = None
if timetype == 'Seconds':
delta = datetime.timedelta(seconds = objectivetime)
else:
delta = datetime.timedelta(minutes = objectivetime)
objtime = a + delta
This will give you a datetime object like datetime.now()
To compare the datetime object, you can simply use the comparison operators. For example,
b <= objtime # Finished before (or on) the objective time
b > objtime # Finished after the objective time
You don't even need to subtract a from b! If you still want to, then compare the time deltas instead
elapsed_time <= delta # Finished before (or on) the objective time
elapsed_time > delta # Finished after the objective time
import struct
from collections import namedtuple
StructDeviceInfo = namedtuple('DeviceInfo', ['DeviceID', 'Capturing','Receiving','Socket','DateTime'])
DeviceInfoList = []
def threaded_function():
while True:
if any(x.Capturing == True and x.Datetime in DeviceInfoList different second > 5 for x in DeviceInfoList) : #here,how to do on here?
print('True')
if the DeviceInfoList array inside the Capturing Value is TRUE and at the same time the Datetime are different with datetime.now are more than 5 second. then print true,how to do this?
p/s:the Capturing is TRUE and datetime is more than 5 seconds,must be same array index .
delta = datetime.datetime.now() - x.Datetime
if delta.total_seconds() > 5:
# difference is greater than 5 seconds
Applied to your example, assuming that x.Datetime actually is a datetime.datetime object:
if any((
x.Capturing == True and
(datetime.datetime.now() - x.Datetime).total_seconds() > 5
) for x in DeviceInfoList):
I need to generate four datetime objects in Python:
"The next instance of 5:30AM EST"
"The next instance of 8:30AM EST"
"The next instance of 1:00PM EST"
"The next instance of 5:30PM EST"
Then I need to find which of those is closest to the current date/time.
I wish I could say I have some starting code, but I have no idea where to start on this one.
This should get you started. I have the current time being passed into the function as a datetime, so if the argument is in EST, this should just work.
def find_next(cur_dt):
import datetime as dt
t = [dt.time(5,30), dt.time(8,30), dt.time(13,0), dt.time(17,30)]
cur_t = cur_dt.time()
cur_d = cur_dt.date()
for i in range(len(t)):
if t[i] > cur_t:
rt = [t[(j+i)%len(t)] for j in range(len(t))]
rd = [cur_d] * (len(t)-i) + [cur_d + dt.timedelta(days=1)]*i
return [dt.datetime.combine(rd[j],rt[j]) for j in range(len(rt))]
# everything happens tomorrow
return [dt.datetime.combine(cur_d + dt.timedelta(days=1), i) for i in t]
The result will be the objects, in order, starting with the "soonest" one, and so on.
This seems like it might be a homework question. Is this enough sample code to get you started? It's probably not the MOST efficient, but it'll work.
from datetime import datetime, time, timedelta
now = datetime.now()
today = datetime.date(now)
tomorrow = today + timedelta(days=1)
time_a = time (4, 0)
today_a = datetime.combine(today, time_a)
tomorrow_a = datetime.combine(tomorrow, time_a)
if (today_a - now)>timedelta(0):
print "%s is in the future" % today_a
if (tomorrow_a - now)>timedelta(0):
print "%s is in the future" % tomorrow_a
For a list of times, "t", you can use:
t = [time(5,30), time(8,30), time(13,0), time(17,30)]
now = datetime.now()
today = [x for x in t if datetime.combine(today, x) > now]
not_today = set(t) - set(today)
at the start and end of my program, I have
from time import strftime
print int(strftime("%Y-%m-%d %H:%M:%S")
Y1=int(strftime("%Y"))
m1=int(strftime("%m"))
d1=int(strftime("%d"))
H1=int(strftime("%H"))
M1=int(strftime("%M"))
S1=int(strftime("%S"))
Y2=int(strftime("%Y"))
m2=int(strftime("%m"))
d2=int(strftime("%d"))
H2=int(strftime("%H"))
M2=int(strftime("%M"))
S2=int(strftime("%S"))
print "Difference is:"+str(Y2-Y1)+":"+str(m2-m1)+":"+str(d2-d1)\
+" "+str(H2-H1)+":"+str(M2-M1)+":"+str(S2-S1)
But when I tried to get the difference, I get syntax errors.... I am doing a few things wrong, but I'm not sure what is going on...
Basically, I just want to store a time in a variable at the start of my program, then store a 2nd time in a second variable near the end, then at the last bit of the program, compute the difference and display it. I am not trying to time a function speed. I am trying to log how long it took for a user to progress through some menus. What is the best way to do this?
The datetime module will do all the work for you:
>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000
If you don't want to display the microseconds, just use (as gnibbler suggested):
>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43
from time import time
start_time = time()
...
end_time = time()
seconds_elapsed = end_time - start_time
hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
Both time.monotonic() and time.monotonic_ns() are correct. Correct as in monotonic.
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> t0 = time.monotonic()
>>> time.sleep(1)
>>> t1 = time.monotonic()
>>> print(t1 - t0)
1.001658110995777
Regardless of language, monotonic time is the right answer, and real time is the wrong answer. The difference is that monotonic time is supposed to give a consistent answer when measuring durations, while real time isn't, as real time may be adjusted – indeed needs to be adjusted – to keep up with reality. Monotonic time is usually the computer's uptime.
As such, time.time() and datetime.now() are wrong ways to do this.
Python also has time.perf_counter() and time.perf_counter_ns(), which are specified to have the highest available resolution, but aren't guarranteed to be monotonic. On PC hardware, though, both typically have nanosecond resolution.
Here is a piece of code to do so:
def(StringChallenge(str1)):
#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0
def time_dif(h1,m1,h2,m2):
if(h1 == h2):
return m2-m1
else:
return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0
if str1[1] == ':':
h1=int(str1[:1])
m1=int(str1[2:4])
else:
h1=int(str1[:2])
m1=int(str1[3:5])
if str1[-7] == '-':
h2=int(str1[-6])
m2=int(str1[-4:-2])
else:
h2=int(str1[-7:-5])
m2=int(str1[-4:-2])
if h1 == 12:
h1 = 0
if h2 == 12:
h2 = 0
if "am" in str1[:8]:
flag1 = 0
else:
flag1= 1
if "am" in str1[7:]:
flag2 = 0
else:
flag2 = 1
if flag1 == flag2:
if h2 > h1 or (h2 == h1 and m2 >= m1):
count_min += time_dif(h1,m1,h2,m2)
else:
count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
count_min += (12-h1-1)*60
count_min += (60 - m1)
count_min += (h2*60)+m2
return count_min