17 Time, Schedule Tasks, Launch Programmes Flashcards
Which code …
- calculates how much time passed?
- shows you your current time
- rounds float numbers
import time
1. >>>start = time.time() >>>.... *wait* >>>end = time.time() >>>start - end
- > > > time.ctime()
3. round(spam, nr), e.g.: >>>spam = time.time() >>>round(spam, 2) >>>spam 1597662469.85
How can you do arithmetic with dates or display them in a more convenient way?
- Get current time
- Save a certain day to a variable and then acess its year, month and day`
- Can you compare “the size” of different datetime objects?
“datetime” module
- > > > import datetime
datetime.datetime.now()
datetime.datetime(2020, 8, 17, 15, 33, 47, 126377) - > > > dt = datetime.datetime(2019,10, 21,16,29,0)
dt.year, dt.month, dt.day
(2019, 10, 21)
3. Yes - there is a sequence of time, which even took place earlier etc. Thus: == != >
How can you convert unix epoch timestamp to datetime?
What is a benefit of converting datetime?
datetime.datetime.fromtimestamp(epoch)
e.g.:
“epoch” could be 1.000.000 to receive the time 1.000.000 seconds after 1970
or it could be time.time() for the current time stamp
Benefit:
Datetime object is converted to current time zone
Summarize the 3 Python Timefunctions
- A Unix epoch timestamp (used by the time module) is a float or integer value of the number of seconds since 12 AM on January 1, 1970, UTC.
- A datetime object (of the datetime module) has integers stored in the attributes year, month, day, hour, minute, and second.
- A timedelta object (of the datetime module) represents a time duration, rather than a specific moment.
Name 2x datetime and 2x timedelta functions incl. outcomes
Datetime:
datetime.datetime.now() This function returns a datetime object of the current moment.
datetime.datetime.fromtimestamp(epoch) This function returns a datetime object of the moment represented by the epoch timestamp argument.
Timedelta:
datetime.timedelta(weeks, days, hours, minutes, seconds, milliseconds, microseconds)
This function returns a timedelta object representing a duration of time. The function’s keyword arguments are all optional and do not include month or year.
total_seconds() This method for timedelta objects returns the number of seconds the timedelta object represents.
Multiple Threading:
- What is the advantage?
- How can you create multiple Threads?
Advantage: Use computing or internet broadband capabilities fully
import threading, time
print(‘Start of program.’)
➊ def takeANap():
time.sleep(5)
print(‘Wake up!’)
➋ threadObj = threading.Thread(target=takeANap)
➌ threadObj.start()
print(‘End of program.’)
What gets printed out last?
import threading, time
print(‘Start of program.’)
➊ def takeANap():
time.sleep(5)
print(‘Wake up!’)
➋ threadObj = threading.Thread(target=takeANap)
➌ threadObj.start()
print(‘End of program.’)
“Wake up!” is printed last, as it takes 5seconds to be printed.
The program only stops running once all threads reached their end.
- Can a new thread take arguments?
- If so, how would you run this print call in its own thread?:
»> print(‘Cats’, ‘Dogs’, ‘Frogs’, sep=’ & ‘)
- Yes
- The print call has 3 args and 1 kwarg “sep=’ & ‘”
In threading.Thread():
Arguments: Pass as a list
Karguments: specify as dict
> > > import threading
threadObj = threading.Thread(target=print, args=[‘Cats’, ‘Dogs’, ‘Frogs’],
kwargs={‘sep’: ‘ & ‘})
threadObj.start()
What are concurrency issues and how can you avoid them?
Issues that appear when multiple threads access and modify the same variables simultaneously. -> Hard to reproduce, difficult to debug
THUS:
Make sure new Thread Objects only access local variables
How can you launch other programs with Python?
What 2 functions are useful in this context?
Popen(‘file’) -> P stands for process
> > > import subprocess
calc = subprocess.Popen(‘C:\Windows\System32\calc.exe’)
Useful 2:
calc. wait() # returns “0” once program is closed
calc. poll() # return None when program runs, “0” when closed
How to pass cmd line arguments to Popen() Function
Pass a list as the sole arg to Popen()
- First string in list will be the executable filename of the program
-Subsequent strings will be cmd line args to pass the program when it starts
»> subprocess.Popen([‘C:\Windows\notepad.exe’, ‘C:\Users\Al\hello.txt’])
How do you open Files with DEFAULT applications?
Some programs are already set up with an association, e.g. double-click .txt-file will open txt editor.
To start such a program on windows:
> > > import subprocess
subprocess.Popen([‘start’, ‘hello.txt’], shell=True)
Don´t forget “shell=True”!