Day 3

Task Schedule




Olly and Jamie

Book

Contents:

1. Basic python

  • Statement Assignment
  • print()
  • list/list slice
  • for loop + list (range)
  • while loop
  • str()
  • function

2. Third-party modules

Check Modules Exist

You don't need to install time/datetime/threadin/subprocess, because they are in standard library.

Without Error Massage!!

import time
import datetime
import threading
import subprocess

Let's Start!

Time Module

time.time() Function

  • Unix epoch is a time reference commonly used in programming
  • Start calculated the seconds form 12 AM on January 1, 1970
  • The time.time() function returns the number of seconds since that moment as a float value

Example

The return value is how many seconds have passed from the Unix epoch till now

In [1]:
import time
time.time()
Out[1]:
1529772044.2020128
In [2]:
startTime = time.time()
result = 1
for i in range(1, 10):
    result = result * i
    print(i, result)
endTime = time.time()

duration = endTime - startTime
print('Cost time : %s' %(duration))
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
Cost time : 0.0010063648223876953

time.sleep() Function

In [3]:
import time
time.sleep(5)
print('Wakeup Now!')
Wakeup Now!

Notice!

  • If you enter time.sleep(5), you’ll see that the next prompt (>>>) doesn’t appear until five seconds have passed
  • Be aware that pressing CTRL-C will not interrupt time.sleep() in python IDLE
  • python IDLE introduction: https://docs.python.org/3/library/idle.html

To work around this problem, use a for loop...

import time
for i in range(5):
    time.sleep(1)
print('Wakeup Now!')

round() Function

round(number, ndigits)

Python’s built-in round() function, which rounds a float to the precision you specify

Notice!

Difference of round() between Python2 and Python3:

Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, ...

  • Python2: rounding is done away from 0.
  • Python3: rounding is done toward the even choice.

In [4]:
import time
now = time.time()
print (now)
1529772049.7269764
In [5]:
round(now)
Out[5]:
1529772050
In [6]:
round(now, 1)
Out[6]:
1529772049.7
In [7]:
round(now, 3)
Out[7]:
1529772049.727

Datetime Module

  • Display a date in a more convenient format
  • Can do arithmetic with dates (e.g. : show the day of 30 days ago)

The Datetime Module Has Its Own Datetime Data Type

datetime.datetime(year, month, day, hour, minute, second, microsecond)
In [8]:
import datetime

#Get localtime
datetime.datetime.now()
Out[8]:
datetime.datetime(2018, 6, 24, 0, 40, 49, 779979)
In [9]:
#Get UTCtime
datetime.datetime.utcnow()
Out[9]:
datetime.datetime(2018, 6, 23, 16, 40, 49, 798978)
In [10]:
now = datetime.datetime.now()
now.year, now.month, now.day, now.hour, now.minute, now.second
Out[10]:
(2018, 6, 24, 0, 40, 49)

A Unix epoch timestamp converted to a datetime object

datetime.datetime.fromtimestamp(Unix_Epoch)
In [11]:
datetime.datetime.fromtimestamp(1000000)
Out[11]:
datetime.datetime(1970, 1, 12, 21, 46, 40)
In [12]:
datetime.datetime.fromtimestamp(time.time())
Out[12]:
datetime.datetime(2018, 6, 24, 0, 40, 51, 201974)

Datetime Could Apply with Comparison

In [13]:
NewYear = datetime.datetime(2018, 1, 1)
ChristmasDay = datetime.datetime(2018, 12, 25)
In [14]:
NewYear == ChristmasDay
Out[14]:
False
In [15]:
NewYear < ChristmasDay
Out[15]:
True
In [16]:
NewYear != ChristmasDay
Out[16]:
True

Timedelta Data Type

datetime.timedelta(days, hours, minutes, seconds)

Represents a duration of time rather than a moment in time

  • delta.seconds = (10hr X 60 X 60) + (10mins X 60) + 10 seconds = 36610 (seconds)
  • delta.total_seconds() = (10days X 24 X 60 X 60) + 36610 = 900610 (seconds)
In [17]:
delta = datetime.timedelta(days=10, hours=10, minutes=10, seconds=10)
delta.days, delta.seconds
Out[17]:
(10, 36610)
In [18]:
delta.total_seconds()
Out[18]:
900610.0

Notice!

  • There is no month or year keyword argument for input and output
  • Input: weeks, days, hours, minutes, seconds, milliseconds, microseconds
  • Output: days, seconds, microseconds, total_seconds
In [19]:
delta = datetime.timedelta(weeks=1, days=10, hours=10, minutes=10, seconds=10)
delta.days, delta.seconds
Out[19]:
(17, 36610)

It could carry over

In [20]:
delta_2 = datetime.timedelta(days=10, hours=34, minutes=10, seconds=10)
delta_2.days, delta_2.seconds
Out[20]:
(11, 36610)
In [21]:
delta = datetime.timedelta(days=10, hours=10, minutes=10, seconds=10, milliseconds=1000)
delta.days, delta.seconds
Out[21]:
(10, 36611)

Datetime Calculate with Operators

In [22]:
import datetime
dt = datetime.datetime.now()
dt
Out[22]:
datetime.datetime(2018, 6, 24, 0, 40, 54, 191976)
In [23]:
thousandDays = datetime.timedelta(days=1000)
In [24]:
dt + thousandDays
Out[24]:
datetime.datetime(2021, 3, 20, 0, 40, 54, 191976)
In [25]:
dt + thousandDays*10
Out[25]:
datetime.datetime(2045, 11, 9, 0, 40, 54, 191976)

Converting datetime Objects into Strings

Strftime Directive Meaning
%Y Year with century, as in '2014'
%y Year without century, '70' to '99' (1970 to 1999) & '00' to '69' (2000 to 2069)
%m Month as a decimal number, '01' to '12'
%B Full month name, as in 'November'
%b Abbreviated month name, as in 'Nov'
%d Day of the month, '01' to '31'
%j Day of the year, '001' to '366'
%w Day of the week, '0' (Sunday) to '6' (Saturday)
%A Full weekday name, as in 'Monday'
%a Abbreviated weekday name, as in 'Mon'
%H Hour (24-hour clock), '00' to '23'
%I Hour (12-hour clock), '01' to '12'
%M Minute, '00' to '59'
%S Second, '00' to '59'
%p 'AM' or 'PM'
.strftime(format)
In [26]:
import datetime
oct14st = datetime.datetime(2018, 10, 14, 17, 2, 3)
oct14st.strftime('%Y/%m/%d %H:%M:%S')
Out[26]:
'2018/10/14 17:02:03'
In [27]:
oct14st.strftime('%I:%M %p')
Out[27]:
'05:02 PM'
In [28]:
oct14st.strftime("%B of '%y")
Out[28]:
"October of '18"

Converting Strings into datetime Objects

datetime.datetime.strptime(date_string, format)
In [29]:
datetime.datetime.strptime('October 14, 2018', '%B %d, %Y')
Out[29]:
datetime.datetime(2018, 10, 14, 0, 0)
In [30]:
datetime.datetime.strptime('2018/10/14 01:02:03', '%Y/%m/%d %H:%M:%S')
Out[30]:
datetime.datetime(2018, 10, 14, 1, 2, 3)
In [31]:
datetime.datetime.strptime("October of '18", "%B of '%y")
Out[31]:
datetime.datetime(2018, 10, 1, 0, 0)

Multithreading

What's process?

What's thread?

import time, datetime

startTime = datetime.datetime(2029, 10, 31, 0, 0, 0)
while datetime.datetime.now() < startTime:
    time.sleep(1)

print('Program now starting on Halloween 2029')
  • For the example above, your program cannot do anything while waiting till 2029/10/31
  • This is because Python programs by default have a single thread of execution

For Avoiding this Problem, Try "Multithreaded Program" Now!

Normal Program V.S. Threading Program

Normal Program

In [32]:
import threading, time

print('Start of program.')

def takeANap():
    time.sleep(5)
    print('Wake up!')
    
takeANap()

print('End of program')
Start of program.
Wake up!
End of program

Threading Program

In [33]:
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')
Start of program.
End of program

Passing Arguments to the Thread’s Target Function

threading.Thread(target, kwargs)
In [34]:
print('Cats', 'Dogs', 'Frogs', sep=' & ')
Cats & Dogs & Frogs
In [35]:
import threading
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'], kwargs={'sep': ' & '})
threadObj.start()
Cats & Dogs & Frogs

Notice!

  • The concurrency issues may happen when threads read and write variables at the same time.

Launching Other Programs from Python

For Windows

import subprocess
subprocess.Popen('C:\\Windows\\System32\\calc.exe')

For OS X

import subprocess
subprocess.Popen(['open', '/Applications/Calculator.app/'])

For Ubuntu Linux

import subprocess
subprocess.Popen(['see', '/usr/bin/gnome-calculator'])

Open Files with Default Application

Use 'start' for Windows

import subprocess
subprocess.Popen(['start','OOOO.txt'], shell=True)

Use 'open' for OS X

import subprocess
subprocess.Popen(['open', 'OOOO.txt'])

Use 'see' for Ubuntu Linux

import subprocess
subprocess.Popen(['see', 'OOOO.txt'])

Create an New Text File and Open with Default Application

In [38]:
fileObj = open('D3_01.txt', 'w')
fileObj.write('Hello world!')
fileObj.close()

import subprocess
subprocess.Popen(['start', 'D3_01.txt'], shell=True)
Out[38]:
<subprocess.Popen at 0x1a331243dd8>

Running Other Python Scripts

Where is your python3 location?

On Windows terminal

> where python3

On OS X & Ubuntu Linux terminal

$ which python3

Create an New Python File and Running Script

For Windows

import subprocess
subprocess.Popen([r'C:\Program Files\Python36\python3.exe', 'D3_02.py'])

For OS X & Ubuntu Linux

import subprocess
subprocess.Popen([r'/usr/bin/python3', 'D3_02.py'])
In [39]:
fileObj = open('D3_02.py', 'w')
fileObj.write('print("Hello Jamie!")')
fileObj.close()

subprocess.Popen([r'C:\Program Files\Python36\python3.exe', 'D3_02.py'])
Out[39]:
<subprocess.Popen at 0x1a331243908>

Project : Create a Task for Out-of-office Notification

  1. Choose notification picture you like
  2. Count for the current DateTime
  3. Before the time you could get off, use time.sleep(1) and refresh the current time at the end of loop
  4. If times up, open picture with subprocess.Popen()
import time, datetime, subprocess
In [40]:
import time, datetime, subprocess

now = datetime.datetime.now()
print(now)

while now.minute!=42:
    time.sleep(1)
    now = datetime.datetime.now()
    print(str(now.minute)+':'+str(now.second), end='>')
    
subprocess.Popen(['start', 'snoopy.JPG'], shell=True)
2018-06-24 00:41:30.914973
41:31>41:32>41:33>41:34>41:35>41:36>41:37>41:38>41:39>41:40>41:41>41:42>41:43>41:44>41:45>41:46>41:47>41:48>41:49>41:50>41:51>41:52>41:53>41:54>41:55>41:56>41:57>41:58>41:59>42:0>
Out[40]:
<subprocess.Popen at 0x1a33124a668>

Exercise

Simple Countdown Program

Step 0 : Choose Notification Music You like

Step 1: Count Down

Step 2: Play the Sound File

Answer

In [41]:
import time, subprocess

timeLeft = 5
while timeLeft > 0:
    print(timeLeft, end='>')
    time.sleep(1)
    timeLeft = timeLeft - 1

subprocess.Popen(['start', 'Sleep_Away.mp3'], shell=True)
5>4>3>2>1>
Out[41]:
<subprocess.Popen at 0x1a33124a0f0>

def Day3End() :

     return 'Thank U ❤'