I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.
The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?
I've tried numerous variations of the code below:
import os
import time
import datetime
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")
sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st
os.system(sys_call)
I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.
Perhaps using Python is overkill here. Since your task scheduler is probably already invoking a shell when it invokes Python, let's just have the shell do the work.
Use this command for your command scheduler:
fswebcam -r 1280x720 /home/pi/python/projectx_images/$(date +%Y-%m-%d_%H:%M:%S)
Assuming...
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S') <--- close with " instead of '
isn't your problem... I've used the following code and it works for me.
ti = datetime.datetime.utcfromtimestamp(time.time()).strftime("%y-%m-%d_%H:%M:%S")
outputs...
'17-11-18_01:47:48'
Note: This outputs in UTC +0:00 so you'd need to apply another operation on it to get it to your timezone. Since time.time() returns a UNIX epoch time in seconds, you'd need to offset the time by however much faster/slower your timezone is, in relation to UTC +0:00, in seconds.
I.e. if you're in EST time, then you'd apply utcfromtimestamp() on time.time() - 18000 to get the time for your timezone.
ti = datetime.datetime.utcfromtimestamp(time.time() - 18000).strftime("%y-%m-%d_%H:%M:%S")
Related
I have to perform several experiments in order to analyse certain results for a class assignment. For each result, I have to run a line of code by varying the parameters from terminal. I was wondering if there is a way to automate this and thus save me the trouble of running the program and changing the values each time. Attached is the line of code that I have to execute each time:
teaa/examples/scripts/run-python.sh teaa/examples/python/rf_mnist.py \
--numTrees 10 --maxDepth 7 --pcaComponents 40
I would like these lines of code to be executed n times automatically and that in each execution, the parameters 'numTrees, maxDepth and pcaComponents' change in a set range of values.
I have not really tried any solutions yet. I have never programmed in terminal and I have no idea where to start.
For more involved process operations, one should use the subprocess module in stdlib Python... but if you just want a one-off run of this command line, you can just use plain old os.system function - The followin code:
import os
for nt in range(1,21):
for md in range(1,11):
for pc in range(20,100,10):
os.system(f'teaa/examples/scripts/run-python.sh teaa/examples/python/rf_mnist.py --numTrees {nt} --maxDepth {md} --pcaComponents {pc}')
will run your program for numTrees = 1,2...20, maxDepth = 1,..10 and pcaComponents = 20,...90
I have been given a python script which allows me to mute the volume of my mac at a time I set so that any podcasts I'm listening to as I fall asleep won't wake me up once I am asleep.
However, it will only act once the time given happens on that day, therefore if I try to activate it before midnight, it will mute the laptop immediately, which is not ideal because if I want to use it I have to wait for midnight to pass before I go to sleep.
#!/usr/bin/env python3
import datetime as dt
import osascript
import sys
from threading import Timer
def do_the_biz():
osascript.osascript("set volume output volume 0")
print("Night night")
today = dt.datetime.now()
dateString = today.strftime('%d-%m-%Y') + " " + sys.argv[1]
newDate = today.strptime(dateString,'%d-%m-%Y %H:%M')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,do_the_biz,()).start()
So, a typical execution of this script looks like this:
$./sleep.py 04:00
and the command line will return the following once it has reached 4am, and then close the program:
Night Night
What I would like is to be able to manipulate the date so that the script will operate at the next available time of, for example, 4am - so it would essentially operate almost in the exact same way an alarm would. For this I could run an entirely different script of sleep.tomorrow.
However, in an ideal world, I would like to be able to:
have the option to have another argument where I specify today or tomorrow and the program acts accordingly;
be able to cancel the process without having to close the terminal.
I am new to python and have been having a hard time understanding the differences between the various datetime functions and the documention hasn't helped, so a brief explanation and comparison between what they input and output and how they interact would be gratefully appreciated.
I am measuring the response time on a function using the time module. The time module is supposed to output seconds as a float, so I am saving a start time value (time.clock()) and taking another reading at the end, and using the difference as a runtime. While watching the results, we noted the runtimes seemed high -- something that seemed to take less than 2 seconds, was printing as 3-and-change, for instance. Based on the perceived issue, I decided to double-check the results using the datetime module. Printing the two side-by-side shows the time module values are almost double the datetime values.
Anyone know why that might be?
Here is my code:
for datum in data:
start = datetime.datetime.now()
startts = time.clock()
check = test_func(datum)
runtime = datetime.datetime.now() - start
runts = time.clock() - startts
print(check, "Time required:", runtime, "or", runts)
Some of my results:
XYZ Time required: 0:00:01.985303 or 3.7836029999999994
XYZ Time required: 0:00:01.476289 or 3.3465039999999817
XYZ Time required: 0:00:01.454407 or 3.7140109999999993
XYZ Time required: 0:00:01.550416 or 3.860824000000008
I am assuming this sort of issue would have been noticed before, and I am just missing something basic in my implementation. Can someone clue me in?
Looks like time.clock() has been Deprecated since version 3.3
Maybe this will help ?
time.clock()
On Unix, return the current processor time as a floating point number
expressed in seconds. The precision, and in fact the very definition
of the meaning of “processor time”, depends on that of the C function
of the same name.
On Windows, this function returns wall-clock seconds elapsed since the
first call to this function, as a floating point number, based on the
Win32 function QueryPerformanceCounter(). The resolution is typically
better than one microsecond.
Deprecated since version 3.3: The behaviour of this function depends
on the platform: use perf_counter() or process_time() instead,
depending on your requirements, to have a well defined behaviour.
We found the issue. The test_func I am testing is using a multi-threaded process. I both did not know that, and did not know it was an issue.
The time module uses processor time (https://docs.python.org/3.6/library/time.html), while the datetime module uses wall clock time (https://docs.python.org/3.6/library/datetime.html). Using the difference in the datetime timestamps told me how much actual time had elapsed, and for our purposes was the relevant information.
I hope this helps someone else in the future!
I'm working on a Python program which will be running on users computer. The program should be idle as much as possible between actions (3 per day). Actions should be at morning, afternoon and in the night.
So I want to tell the program that it has to run (to instantiate a class and do some methods from it) at three certain times every day.
I know about one way but it is an overkill I think.
while True:
time = time.now()
if time in [08:00 am, 12:30pm, 08:00 pm]:
#Do what you have to do
Can you advise me the best approach to program like this? This program will run not on my computer so I would like to manage everything as a one component.
EDIT: Martin advise me to use cron job. Is it possible to set everything in a Python code so I don't have to change anything on a clients PC?
Since you are on Windows, consider using the SCHTASKS command:
Schedules commands and programs to run periodically or at a
specific time. Adds and removes tasks from the schedule, starts and
stops tasks on demand, and displays and changes scheduled tasks.
Your command should look like:
schtasks /create /tn <TaskName> /tr <TaskRun> /sc hourly [/mo {1 - 23}] [/st <HH:MM>] [/sd <StartDate>] [/ed <EndDate>]
/mo is the repeat interval
For the complete documentation refer to:
https://technet.microsoft.com/en-ca/library/cc725744.aspx
Only if you do not have access to clients PC , you can do something like - calculate the time now using datetime library , then take the different between the next time you want to run the program and now , then sleep for that much amount of seconds using time.sleep . When you wake up , again run whatever you want , and then again do same thing calculate time between now and next time you want to run the program.
Example code -
from datetime import datetime
import time
while True:
nw = datetime.now()
nw
>> datetime.datetime(2015, 6, 22, 17, 57, 5, 668002)
t = datetime(nw.year,nw.month,nw.day,22,0,0,0) # this is where you calculate next time you want to run the program.
t
>> datetime.datetime(2015, 6, 22, 22, 0)
td = t - nw
td.seconds
>> 14574
time.sleep(14574)
#<do your stuff>
Please note in above code , >> indicates the printed value of the previous statements, and they are not part of the code.
Though I am not sure, if there are any side-effects (bad-effects) of making a process sleep for very long.
If you have access to client's PC , or can make him run a task scheduler or in unix , cronjob , consider that as the better option.
I am trying to test how long my battery runs on my raspberry pi. All i need to do is run a while loop until the battery dies. However, I need to record the time that it starts and ends. I would like to save the data into a txt file. My current code is as follows:
import time
file = open('time','w')
x=1
while x==1:
from datetime import datetime
now = datetime.now()
file.write(now)
file.close()
If I just print the results in python i will get a result, and the current code makes a file called 'file' but there is nothing saved in the txt file. Any and all help would be appreciated.
Thank you for your time
You have an infinite loop which just gets the current time over and over again ... This loop won't break (even if your battery dies ...).
At some point, you need to break the loop or the condition in the while needs to become False. e.g.
from datetime import datetime
while x == 1:
now = datetime.now()
break
or
from datetime import datetime
while x == 1:
now = datetime.now()
x += 1
Generally speaking, you'll want to look in your system logs for when the computer decided to start up and when it decided to shut down due to lack of battery power ...
I would recomend code that looks like the following:
import time
import datetime.datetime as dt
initTime = dt.now()
while True:
with open('time.txt', 'a') as f:
f.write( str(dt.now() - initTime) )
time.sleep(1)
The couple of differences. First, you always open the file in append mode. This way, the file will be flushed every time. Next, it will always update the file with the amount of time elapsed. So even if your raspberry pi shuts down, you should be able to recover it.
No need to record these times yourself. The Pi (and almost any Linux distribution) writes those events to the /var/log/wtmp file (more about that file here). The last command can retrieve those events (also see the manual entry for last). Try the following:
last -FRx | grep -e 'boot\|shutdown'
Explanation of the flags:
-F prints the full date and times - which is handy in your case, because that's what you wanted to know.
-R suppresses the hostname in the output. You don't need that.
-x shows shutdown en runlevel changes - now that's what you wanted to know.
Finally the grep statement filters out the boot or shutdown messages.