Day 3

Task Schedule




Olly

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]:
1511599245.4871345
In [12]:
s1 = time.time()
result = 1
for i in range(1, 10):
    result = result * i
    print(i, result)
s2 = time.time()

duration = s2 - s1
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.0009999275207519531

TIME.SLEEP() Function

In [18]:
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

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

import time
for i in range(20):
    time.sleep(1)

round() Function

round(number, ndigits)

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

In [21]:
import time
now = time.time()
round(now)
Out[21]:
1511604084
In [20]:
round(now, 1)
Out[20]:
1511604053.5
In [22]:
round(now, 3)
Out[22]:
1511604084.082

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 [23]:
import datetime
datetime.datetime.now()
Out[23]:
datetime.datetime(2017, 11, 25, 18, 29, 32, 717089)
In [27]:
now = datetime.datetime.now()
now.year, now.month, now.day, now.hour, now.minute, now.second
Out[27]:
(2017, 11, 25, 18, 34, 38)

A Unix epoch timestamp converted to a datetime object

datetime.datetime.fromtimestamp(Unix_Epoch)
In [29]:
datetime.datetime.fromtimestamp(1000000)
Out[29]:
datetime.datetime(1970, 1, 12, 21, 46, 40)
In [30]:
datetime.datetime.fromtimestamp(time.time())
Out[30]:
datetime.datetime(2017, 11, 25, 18, 38, 59, 270808)

Datetime Could Apply with Comparison

In [31]:
NewYear = datetime.datetime(2018, 1, 1)
ChristmasDay = datetime.datetime(2018, 12, 25)
In [33]:
NewYear == ChristmasDay
Out[33]:
False
In [32]:
NewYear < ChristmasDay
Out[32]:
True
In [34]:
NewYear != ChristmasDay
Out[34]:
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 [39]:
delta = datetime.timedelta(days=10, hours=10, minutes=10, seconds=10)
delta.days, delta.seconds
Out[39]:
(10, 36610)
In [40]:
delta.total_seconds()
Out[40]:
900610.0

Notice!

  • There is no month or year keyword argument

Datetime Calculate with Operators

In [42]:
import datetime
dt = datetime.datetime.now()
dt
Out[42]:
datetime.datetime(2017, 11, 25, 19, 19, 17, 739012)
In [43]:
thousandDays = datetime.timedelta(days=1000)
In [44]:
dt + thousandDays
Out[44]:
datetime.datetime(2020, 8, 21, 19, 19, 17, 739012)
In [45]:
dt + thousandDays*10
Out[45]:
datetime.datetime(2045, 4, 12, 19, 19, 17, 739012)

Converting datetime Objects into Strings

Strftime Directive Meaning
%Y Year with century, as in '2014'
%y Year without century, '00' to '99' (1970 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 [53]:
import datetime
oct14st = datetime.datetime(2018, 10, 14, 17, 2, 3)
oct14st.strftime('%Y/%m/%d %H:%M:%S')
Out[53]:
'2018/10/14 17:02:03'
In [54]:
oct14st.strftime('%I:%M %p')
Out[54]:
'05:02 PM'
In [55]:
oct14st.strftime("%B of '%y")
Out[55]:
"October of '18"

Converting Strings into datetime Objects

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

Multithreading

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

Threading Program

Passing Arguments to the Thread’s Target Function

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

Notice!

  • The concurrency issues happen when threads read and write variables at the same time.
  • To avoid concurrency issues, never let multiple threads read or write the same variables.

Launching Other Programs from Python

Start an external program from your Python script

On Windows

Right-click the application’s Start menu item and select Properties to view the application’s filename.

On OS X

CTRL-click the application and select Show Package Contents to find the path to the executable file.

Open Application

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 Defualt Application

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

import subprocess
subprocess.Popen(['start', 'Docs\D3_01.txt'], shell=True)
Out[6]:
<subprocess.Popen at 0x4b0ac50>

Running Other Python Scripts

Create an New Python File and Running Script

In [7]:
fileObj = open('Docs\D3_02.py', 'w')
fileObj.write('print("Hello Olly!")')
fileObj.close()

subprocess.Popen([r'C:\Users\Olly\AppData\Local\Programs\Python\Python35\python.exe', 'Docs\D3_02.py'])
Out[7]:
<subprocess.Popen at 0x4b0a668>

Project : Simple Countdown Program

Step 0 : Choose Notification Music You like

Step 1: Count Down

Step 2: Play the Sound File

In [1]:
import time, subprocess

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

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

Exercise

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

Answer

In [38]:
import time, datetime, subprocess

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

while now.minute!=7:
    time.sleep(1)
    now = datetime.datetime.now()
    print(str(now.minute)+':'+str(now.second), end='>')
    
subprocess.Popen(['start', 'Imgs/D3_08.GIF'], shell=True)
2017-11-30 00:06:52.985218
6:53>6:54>6:55>6:56>6:57>6:58>6:59>7:0>
Out[38]:
<subprocess.Popen at 0x51bf9e8>

def Day3End() :

     return 'Thank U ❤'