Skip to content

Commit 321d1df

Browse files
committed
Chapter 15 finished.
1 parent 3bf0bfd commit 321d1df

11 files changed

+142
-0
lines changed

15-time/README.md

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# time
2+
<pre>
3+
import time
4+
now = time.time()
5+
</pre>
6+
7+
# datetime
8+
1. import datetime
9+
2. datetime.datetime.now()
10+
3. datetime.datetime.fromtimestamp(time.time())
11+
4. datetime.timedelta()
12+

15-time/about30YearsLater.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import datetime
2+
3+
aboutThirtyYears = datetime.timedelta(days=365*30)
4+
print(datetime.datetime.now() + aboutThirtyYears)

15-time/calcProd.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import time
2+
startTime = time.time()
3+
# Calculate the product of the first 100,000 numbers.
4+
product = 1
5+
for i in range(1, 100000):
6+
product = product * i
7+
endTime = time.time()
8+
print('The result is %s digits long.' % (len(str(product))))
9+
print('Took %s seconds to calculate.' % (endTime - startTime))

15-time/countdown.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#! python3
2+
# countdown.py - A simple countdown script.
3+
4+
import time, subprocess
5+
6+
timeLeft = 10
7+
while timeLeft > 0:
8+
print(timeLeft, end='')
9+
time.sleep(1)
10+
timeLeft = timeLeft - 1
11+
12+
# At the end of the countdown, play a sound file.
13+
subprocess.Popen(['start','alarm.wav'], shell=True)

15-time/multidownloadXkcd.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#! python3
2+
# multidownloadXkcd.py - Downloads XKCD comics using multiple threads.
3+
4+
import requests, os, bs4, threading
5+
os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd
6+
7+
def downloadXkcd(startComic, endComic):
8+
for urlNumber in range(startComic, endComic):
9+
# Download the page.
10+
print('Downloading page http://xkcd.com/%s...' % (urlNumber))
11+
res = requests.get('http://xkcd.com/%s' % (urlNumber))
12+
res.raise_for_status()
13+
14+
soup = bs4.BeautifulSoup(res.text)
15+
16+
# Find the URL of the comic image.
17+
comicElem = soup.select('#comic img')
18+
if comicElem == []:
19+
print('Could not find comic image.')
20+
else:
21+
comicUrl = comicElem[0].get('src')
22+
# Download the image.
23+
print('Downloading image %s...' % (comicUrl))
24+
res = requests.get(comicUrl)
25+
res.raise_for_status()
26+
27+
# Save the image to ./xkcd
28+
imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
29+
for chunk in res.iter_content(100000):
30+
imageFile.write(chunk)
31+
imageFile.close()
32+
33+
# Create and start the Thread objects.
34+
downloadThreads = [] # a list of all the Thread objects
35+
for i in range(0, 1400, 100): # loops 14 times, creates 14 threads
36+
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))
37+
downloadThreads.append(downloadThread)
38+
downloadThread.start()
39+
40+
# Wait for all threads to end.
41+
for downloadThread in downloadThreads:
42+
downloadThread.join()
43+
print('Done.')

15-time/stopwatch.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#! python3
2+
# stopwatch.py - A simple stopwatch program.
3+
4+
import time
5+
6+
# Display the program's instructions.
7+
print('Press enter to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
8+
input() # press Enter to begin
9+
print('Started.')
10+
startTime = time.time() # get the first lap's start time
11+
lastTime = startTime
12+
lapNum = 1
13+
14+
# Start tracking the lap times.
15+
try:
16+
while True:
17+
input()
18+
lapTime = round(time.time() - lastTime, 2)
19+
totalTime = round(time.time() - startTime, 2)
20+
print('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime), end='')
21+
lapNum += 1
22+
lastTime = time.time() # reset the last lap time
23+
except KeyboardInterrupt:
24+
# Handle the Ctrl-C exception to keep its error message from displaying.
25+
print('\nDone.')

15-time/thousandDaysLater.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import datetime
2+
3+
dt = datetime.datetime.now()
4+
thousandDays = datetime.timedelta(days=1000)
5+
print(dt + thousandDays)

15-time/threadDemo.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import threading, time
2+
print('Start of program.')
3+
4+
def takeANap():
5+
time.sleep(5)
6+
print('Wake up!')
7+
8+
threadObj = threading.Thread(target=takeANap)
9+
threadObj.start()
10+
11+
print('End of program.')

15-time/threadWithParameters.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import threading
2+
3+
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],
4+
kwargs={'sep': ' & '})
5+
threadObj.start()
6+

15-time/timeSleep.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import time
2+
3+
for i in range(3):
4+
print('Tick')
5+
time.sleep(1)
6+
print('Tock')
7+
time.sleep(1)
8+

15-time/until.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import datetime
2+
import time
3+
tm = datetime.datetime(2017, 7, 8, 8, 27, 0)
4+
while datetime.datetime.now() < tm:
5+
time.sleep(1)
6+
print('Done')

0 commit comments

Comments
 (0)