Python Different the datetime in a Struct Array - python

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):

Related

Change UTC offset for a time string

I would like to change the time to a manually chosen offset for a timestring
In this example, I will subract 11 hours from the times, but the utc offset would still be 00:00.. How can I do this correctly?
time = "2020-03-03T18:21:19+00:00"
utc_diff = 2
obj1 = datetime.datetime.strptime(
re.sub(r"([\+-]\d\d):(\d\d)(?::(\d\d(?:.\d+)?))?", r"\1\2\3", time),
"%Y-%m-%dT%H:%M:%S%z")
obj1 = obj1 - datetime.timedelta(hours=-utc_diff)
Using this example the result would be
"2020-03-03T20:21:19+00:00"
But I want the offset to change also,:
"2020-03-03T20:21:19+02:00"
This should work for your needs:
def utc_offset(time, offset):
def pad(number):
n = str(abs(number))
while len(n) < 2:
n = "0" + n
if number >= 0:
n = "+" + n
else:
n = "-" + n
return n
utc_diff_format = f"{pad(offset)}:00"
time = list(time)
i = time.index("+")
time[i:] = list(utc_diff_format)
time = ''.join(time)
return time
time = "2020-03-03T18:21:19+00:00"
utc_diff = 2
print(utc_offset(time, utc_diff))
Output:
2020-03-03T18:21:19+02:00
you can pass integer values directly to datetime.timedelta(hours=11)

Comparing Dates string in Python

I need help with the python function of comparing two dates (string) and return True if date1 is ealier than date2. Here is my code but I'm don't know why it returns True for the test case("2013/10/24", "2013/9/24")
# str, str -> boolean
def dateLessThan(date1,date2):
date1 = date1.split('/')
date2 = date2.split('/')
if date1[0] < date2[0]:
return True
elif date1[0] == date2[0] and date1[1] < date2[1]:
return True
elif date1[0] == date2[0] and date1[1] == date2[1] and date1[2] < date2[2]:
return True
else:
return False
Just use the datetime.strptime class method instead of doing your own parsing.
def dateLessThan(date1,date2):
date1 = datetime.datetime.strptime(date1, "%Y/%m/%d")
date2 = datetime.datetime.strptime(date2, "%Y/%m/%d")
return date1 < date2
Consider using datetime objects (assumed your time format is YY/mm/dd)
from datetime import datetime
def dateLessThan(date1,date2):
datetime1 = datetime.strptime(date1, '%Y/%m/%d')
datetime2 = datetime.strptime(date2, '%Y/%m/%d')
return datetime1 < datetime2
your test fails because of lexicographical comparison of strings. "10" < "9".
Without using datetime or time parsing (which is required when there are complex formats, months names...), it's possible to do something simple since there's only numbers involved (and you have years/month/day, so you're close to the ISO date format where you can compare lexicographically).
Just map the values into integers and convert to lists and let the natural/lexicographical order of lists do the rest:
def dateLessThan(date1,date2):
return [int(x) for x in date1.split('/')] < [int(x) for x in date2.split('/')]

Check if current current hour is available in python list

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!"

Calculating Time Difference

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

python time interval algorithm sum

Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).
My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.
Thanks
from datetime import datetime, timedelta
START, END = xrange(2)
def tparse(timestring):
return datetime.strptime(timestring, '%H:%M')
def sum_intervals(intervals):
times = []
for interval in intervals:
times.append((tparse(interval[START]), START))
times.append((tparse(interval[END]), END))
times.sort()
started = 0
result = timedelta()
for t, type in times:
if type == START:
if not started:
start_time = t
started += 1
elif type == END:
started -= 1
if not started:
result += (t - start_time)
return result
Testing with your times from the question:
intervals = [
('16:30', '20:00'),
('15:00', '19:00'),
]
print sum_intervals(intervals)
That prints:
5:00:00
Testing it together with data that doesn't overlap
intervals = [
('16:30', '20:00'),
('15:00', '19:00'),
('03:00', '04:00'),
('06:00', '08:00'),
('07:30', '11:00'),
]
print sum_intervals(intervals)
result:
11:00:00
I'll assume you can do the conversion to something like datetime on your own.
Sum the two intervals, then subtract any overlap. You can get the overlap by comparing the min and max of each of the two ranges.
Code for when there is an overlap, please add it to one of your solutions:
def interval(i1, i2):
minstart, minend = [min(*e) for e in zip(i1, i2)]
maxstart, maxend = [max(*e) for e in zip(i1, i2)]
if minend < maxstart: # no overlap
return minend-minstart + maxend-maxstart
else: # overlap
return maxend-minstart
You'll want to convert your strings into datetimes. You can do this with datetime.datetime.strptime.
Given intervals of datetime.datetime objects, if the intervals are:
int1 = (start1, end1)
int2 = (start2, end2)
Then isn't it just:
if end1 < start2 or end2 < start1:
# The intervals are disjoint.
return (end1-start1) + (end2-start2)
else:
return max(end1, end2) - min(start1, start2)

Categories