I am working on making calibrations for the Raspberry Pi Weather Station I have created using the Sense HAT. The offset between the actual temperature and the reading received from the Pi increases at a certain time of day (when the sun hits the system). I want to subtract a larger number from the Sense HAT temp during this time and revert to the lower number at all other instances.
I attempted to use datetime module to set up the beginning and and end times for the more significant calibration. I set up the current time in a separate variable.
time = datetime.time()
time_start = datetime.time(12,30,00)
time_end = datetime.time(3,15,00)
if time_start < time and time_end > time:
temperature -= 10
else:
temperature -= 8
I expected the output to be a lower temperature reading but the program continues to subtract 8 degrees during this period instead of 10. I did some troubleshooting and when printing the "time" variable it prints as "00:00:00". This would explain why the program skips to the else statement and only subtracts 8.
Any idea on how to solve this?
Using datetime.time() is the equivalent of using time(0, 0, 0).
What you want instead is to obtain the current time, which you can do through datetime.now().
import datetime
time = datetime.datetime.now().time()
time_start = datetime.time(12,30,00)
time_end = datetime.time(3,15,00)
if time_start < time and time_end > time:
temperature -= 10
else:
temperature -= 8
Related
I need to check if current time from NTP server (using ntplib module) is within some required time range.
I have written the below code but I need some help to finish this task.
#!/usr/bin/python
import ntplib
from time import ctime
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org')
print (ctime(response.tx_time))
Output:
Fri Aug 16 13:26:16 2019
Now I need to check the ntp current time "13:26:16" is within the time range "09:30:00 - 15:30:00", so how can we check this in Python?
It must say current ntp time is/not in time range "09:30:00 - 15:30:00"
Convert the epoch timestamp to a suitable representation such as a Python datetime object and inspect the hours and minutes fields.
from time import gmtime
# ...
dt = time.gmtime(response.tx_time)
if (dt.tm_hour == 9 and dt.tm_min >= 30) or (
10 <= dt.tm_hour <= 14) or (
dt.tm_hour == 15 and dt.tm_min <= 30):
print('yes indeed')
else:
print('not')
Time zones are always tricky; the above gets you UTC (as vaguely implied by the name gmtime). If you want to compare to the value in your local time zone, try time.localtime instead.
I will attach my code, but basically I am importing a csv file with start times/end times for picking cases of a particular item. All the cases go to a "cart", which is identified by an ID number. I want to find the total time to pick all the cases. The format of the time is hh:mm:ss and, initially, I was using the datetime module but I could not figure out the documentation, so I ended up just converting all the times to seconds, subtracting end/start for each case, and adding that duration to the total time. In the end, converted total time to hours. Already had number of cases picked total, and divided by total time in hrs to get cases picked per hr. Is this correct logic? I got a number that was very, very low: 7.99 cases/hr, which leads me to believe my timing/duration code is incorrect (already checked that quantity was correct).
#instantiate totalTime to zero
totalTime = 0
#every line/row in file; assume already opened above
for line in lines:
#if there is a different case to pick, find the start time
if taskId != entryList[0]: #this is so it doesnt duplicate times
timestart = entryList[7]
colonStartIndex = timestart.find(":")
hourstart = int(timestart[0:colonStartIndex])
minutestart = int(timestart[colonStartIndex+1:colonStartIndex+3])
colonStartIndex2 = timestart.find(":", colonStartIndex+1)
secondstart = int(timestart[colonStartIndex2 +1:colonStartIndex2 +3])
start = hourstart*3600 + minutestart*60 + secondstart
#start = datetime(year=1, month=1, day=1,hour=hourstart,minute=minutestart,second=secondstart)
#start = datetime.time(start)
timeend = entryList[9]
colonEndIndex = timeend.find(":")
hourend = int(timeend[0:colonEndIndex])
minuteend = int(timeend[colonEndIndex+1:colonEndIndex+3])
colonEndIndex2 = timeend.find(":", colonEndIndex+1)
secondend = int(timeend[colonEndIndex2+1:colonEndIndex2+3])
end = hourend*3600 + minuteend*60 + secondend
#end = datetime(year=1,month=1,day=1,hour=hourend,minute=minuteend,second=secondend)
#end = datetime.time(end)
#duration = datetime.combine(date.today(), end) - datetime.combine(date.today(), start)
duration = end - start
if duration >= 0:
duration = duration
elif duration < 0:
duration = -1*duration
totalTime = totalTime + duration
taskId = entryList[0] #first entry in csv file of each line is cartID
totalTime = totalTime/3600
print(totalTime)
print(quantityCount)
avgNumCases = quantityCount/totalTime
print(avgNumCases)
Thank you so much for any help!! Also, I included the datetime stuff, commented out, so if you could suggest a solution based on that, I am open to it:) I was just frustrated because I spent a good bit of time trying to figure it out, but I'm not super familiar w it and the documentation is pretty hard to understand (esp b/c datetime objects, blah blah)
There is an obvious problem in this section:
duration = end - start
if duration >= 0:
duration = duration
elif duration < 0:
duration = -1*duration
If your start point is 22:00:00 and end point is 21:00:00 your duration will be 1 hour instead of 23 hours.
I am making a program that determines what period in school you are in; the schedules differ on certain days so you can just run the program instead of finding out what schedule you are on.
I am using the 'DateTime' import; but the problem is certain classes may start at let's say 7:45 and end at 9:50. The way I am programming the two times contradict each-other so the text wont be displayed.
here is the snippet of code:
if sch == "A":
if hour >= 7 and min >= 45:
if hour <= 9 and min <= 50:
print("It is period 1; Class ends at 9:50AM")
It was determined previously in the program that we are on schedule 'A' which starts at 7:45AM and ends at 9:50AM. In short I want it to display the message whilst in between those two times.
Use datetime for this task:
from datetime import datetime
begin = '07:45:00'
end = '09:50:00' # for example
current_time = '10:32:13'
FMT = '%H:%M:%S' # format time
if sch == "A":
if datetime.strptime(begin, FMT) < \
datetime.strptime(current_time, FMT) < \
datetime.strptime(end, FMT):
print("It is period 1; Class ends at 9:50AM")
you can try this:
from datetime import time
if sch == "A":
if time(hour=7, minute=45) <= time(hour=hour, minute=minute) <= time(hour=9, minute=45):
print("It is period 1; Class ends at 9:50AM")
As I commented your logic is off because you don't allow for minutes other than anything in the 45-50 range, your are using datetimes so stick to comparing datetimes.time's seeing if the hour and minute are within the range 7:45-9:50.
from datetime import time
# cretate a start and end time
start, end = time(7, 45, 0), time(9, 50, 0)
# pass whatever hour and min are in your code to time
hour_min = time(7, 46)
# check the times falls in the range 7:45-9:50
if start <= hour_min <= end:
print("It is period 1; Class ends at 9:50AM")
I am working on my python code as I want to calulcating on the program time to convert it into minutes. When the program start at 12:00AM and my current time show as 1:00AM. The end time show for the program is 6:00AM, so I want to work out between 1:00AM and 6:00AM to take it away then multiply it by 60 to convert it into minutes.
Example: 6 take away 1 which is 5 then I want to multply it by 60 which it is 300 minutes.
Here is the code:
current_time = int(time.strftime("%M"))
prog_width = self.getControl(int(program_id)).getWidth()
prog_length = int(prog_width) / 11.4 - current_time
prog_length = str(prog_length)
prog_length = prog_length.replace('.0', '')
prog_length = int(prog_length)
print prog_length
Can you please show me an example of how I can calculating between 1:00AM and 6:00AM to take it away then convert it into minutes when multply by 60?
You can use the datetime module
from datetime import timedelta
start = timedelta(hours=1)
end = timedelta(hours=6)
duration = end - start
print duration.total_seconds() / 60
I want to control devices (module Raspberry Pi) in a certain time period. I make a PHP web to config time value in database mysql. Then I get time from database to compare with time in system (real time clock). If system time is in between time in mysql => led on.
Here is my table(name: time) in mysql:
start_time stop_time
07:00:00 (Type: time) 08:00:00 (Type:time)
And here is my code control device:
import MySQLdb
import RPi.GPIO as GPIO
from datetime import date
import time
db_local = MySQLdb.connect("localhost","root","root","luan_van")
with db_local:
cur = db_local.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM time")
rows = cur.fetchall()
start = 0
stop = 0
for row in rows:
start = row['start_time']
stop = row ['stop_time']
tg = strftime("%H:%M:%S", time.localtime())
if( start < tg < stop):
GPIO.output(12, True)
It error "can't compare datetime.timedelta to str".
How can I get system time value format "H:M:S"?
Thank for help.
Your start and stop objects are datetime.timedelta objects; these model time durations, not the time of day. You have two options here:
Produce another timedelta to represent the current time, as a delta since midnight
Convert the start and stop values to actual time-of-day values
You can produce a timedelta for 'now' with:
import datetime
midnight = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
time_since_midnight = datetime.datetime.now() - midnight
then compare that with your start and stop:
if start < time_since_midnight < stop:
In the other direction, converting the start and stop timedeltas to datetime.datetime objects means you need to add them to the midnight object:
import datetime
midnight = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
now = datetime.datetime.now()
if (midnight + start) < now < (midnight + stop):
A variation on the latter could be to just use the .time() components and ignore the date portion, but since you already are basing all dates on 'today' that won't make a difference here.