55284A - Introduction To Python - Chapter9
55284A - Introduction To Python - Chapter9
Topics Covered
The datetime
Th module.
is
do
cu
me
nt
be
lon
ja
No of gtimes,
It was the best gs it was the worst of times,… it was the epoch of belief, it was the epoch of
t t
un apni o NI
incredulity… au l LK
tho kant
@ ADickens
riz Charles N
– A Tale of Two Cities, ed red TES
co if H
pie [Link] WAR
sa JA
llo GT
we AP
d!
Introduction .
Working with dates and times can be tricky in programming. Python has some great built-in modules for helping
with this. You’ll learn about these modules in this lesson.
Th
is
do
Understanding
cu
m
Time
en
tb
elo
N jag ngs
Before we get into theo uPythonta code, to it’s important to understand a little about how computer languages, including
na pnilk NIL
Python, understand time. In u a
thoparticular,
n Ktime
A is not the same across geography. The time in Moscow is different from
riz t@re NTE
the time in New York City. These ed differences
co d iff. Swouldn’t
HW cause too much of a problem if they were consistent, but they
p i co A
are not, in large part because Daylight m
es Saving Time R (DST) is practiced in some parts of the world, but not in others,
all JA
and it goes into effect on different dates and ow times. EvenGT that wouldn’t be too bad if there were some scientific way
ed AP
! .
of determining where and when times were changed. But, alas, there is not. The decision to practice Daylight
Saving Time is a political one, not a scientific one. Because of this, we cannot rely on local times to make exact
calculations. Coordinated Universal Time (UTC) to the rescue. UTC, the successor to GMT (Greenwich Mean
Time), is the standard by which we measure time. The following image shows world time zones as offsets:
Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
jag ng
N s
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
Th
is
World Time Zones do on May 7, 2019 at 12:48 30
cu
me
nt
be
Whether or not you need toloben concerned with UTC time and time offsets will depend on the data with which you
No agta gs to
j
are working and the type un of pproblem NI that you are trying to solve.
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
The Epoch pie om WAR
sa JA
llo GT
we AP
The epoch is the moment that a computer or dcomputer
! language
. considers time to have started. Python considers
the epoch to be January 1, 1970 at midnight (1970-01-01 [Link]). 31 Times before the epoch are expressed
internally as negative numbers.
1. [Link]()
Th
is
do
2. cu
time.perf_counter()
me
nt
be
lon
3. time.process_time() ja gs
N g
4. [Link]()
Absolute Time
Of the clocks, only [Link]() measures the absolute time: the number of seconds since the epoch, and can
be converted to an actual time of day.
Th
is
do
Demo 68: date-time/Demos/what_time_is_it.py
cu
me
nt
be
lon
1. No
import time
ja gta gs to
un p NI
au nilka L
2. tho nt@ KAN
riz red TES
seconds_since_epoch ed= [Link]()
op [Link] HWA
3.
4. ies m
minutes_since_epoch = seconds_since_epoch R / 60
all JA
ow GT
5. hours_since_epoch = minutes_since_epoched A
/ P.60
!
6. days_since_epoch = hours_since_epoch / 24
7. years_since_epoch = days_since_epoch / 365.25
8.
9. print("""s: {:,}
10. Th
m: {:,}
is
d
11. h: {:,} ocu
me
nt
12. d: {:,} be
lon
13. No agta gs to
j
y: {:,}""".format(seconds_since_epoch,
un p NI
au nminutes_since_epoch,
il LK
14.
tho kant AN
ze @
rihours_since_epoch,T
15. d c rediff ESH
op . WA
16. ies com
days_since_epoch, R
all JA
17. ow
years_since_epoch, GT
sep='\n'))
ed AP
! .
Code Explanation
The preceding code will render the following (on March 06, 2020 at [Link]):
Th
is
do
cu
me
nt
s: 1,583,501,301.986899 be
lo
N jag ngs
ou
m: 26,391,688.366448317 tap to
na nil NI
h: 439,861.4727741386th u k an LKA
ori t N
ze @red TES
d: 18,327.56136558911 dc iff. HW
op
y: 50.17812831099003 ies com AR
all JA
ow GT
ed AP
! .
Relative Time
The other clocks return relative times from an indeterminate start time. They are useful in determining differences
between moments
Th of time. The most useful of these will be time.perf_counter() as it provides the most
i
precise [Link] often used to measure how quickly a piece of code runs.
um
en
tb
elo
To illustrate how you would ja use
ng this, assume that you wanted to create a list of random integers between 1 and 100
N g s
and that you needed the list as a string.
The most straightforward way of doing this is to create a loop and concatenate a new random number onto your
string with each iteration.
But string concatenation is much less efficient than appending to a list, so it’s actually faster to create a list, append
a random number with each iteration, and then when the loop is complete join the list into a string.
And for a slightly faster solution, use a list comprehension. Here’s the code:
Th
is
do
cu
Demo 69: date-time/Demos/compare_times.py
me
nt
be
lon
No ja gta gs to
1. import time una pni N
uth lkan ILKA
o riz t @ N
2. import random
ed red TES
co if H
3. pie [Link] WAR
sa JA
4. iterations = int(input('Number llo of iterations:
GT '))
we AP
d! .
5.
6. # Concatenating strings
7. start_time = time.perf_counter()
8. numbers = ''
9. for i in range(iterations):
T
his = [Link](1, 100)
10. num d oc
11. um+= ',' + str(num)
numbers e nt
b
elo
12. end_time = time.perf_counter()
n
No agta gs to
j
13. td1 = end_time
un - pstart_time NI
au nilka L
14. tho nt@ KAN
riz re TE
ed SH
15. # Appending to a list co diff.c
pie om WAR
16. start_time = time.perf_counter() sa JA
llo GT
we AP
17. numbers = [] d ! .
18. for i in range(iterations):
19. num = [Link](1, 100)
20. [Link](str(num))
21. numbers = ', '.join(numbers)
22. Th
end_time
is = time.perf_counter()
do
23. cu
td2 = end_time - start_time
m en
tb
24. elo
ja ng
25. N
# Using a list g tap s to
o u comprehension
na n N
26. uth ilkan ILKA
start_time = time.perf_counter()
ori t N
ze @red TES 100)) for i in range(1, iterations)]
27. dc
numbers = [str([Link](1, iff. HW
op
28. numbers = ', '.join(numbers) ies com AR
all JA
ow GT
29. end_time = time.perf_counter() ed AP
! .
30. td3 = end_time - start_time
31.
32. print(f"""Number of numbers: {iterations:,}
33. Time Delta 1: {td1}
34. Time TDelta
h 2: {td2}
is
35. Time Delta
d
oc 3: {td3}
um
en
36. tb
td1 is {round(td1/td3, 2)}x slower than td3.\n""")
elo
jag ng
N s
Code Explanation
And here are the results using different values for integers:
Notice that the speed differential increases markedly when dealing with large amounts of data.
time.struct_time(tm_year=1970,
tm_mon=1, # 1 = January
T
his
tm_mday=1,
d oc
um
tm_hour=0, e nt
be
tm_min=0, lo
N jag ngs
tm_sec=0,
tm_wday=3, # 3 = Thursday (0 = Monday)
tm_yday=1, # 1 = First day of year
tm_isdst=0) # 0 = No daylight savings time
Th
is
oc d
'Thu Jan um
1 [Link] 1970'
en
tb
elo
n
No jagta gs to
un p NI
au nilka
Methods that create time.struct_time L objects include [Link]() and [Link]().
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
[Link]([secs]) llo GT
we AP
d! .
Th
is
do
cu
en
Tomorrow as struct_time
m
tb
elo
ng
>>> day_in_seconds j = 60*60*24
a
N g s
>>> tomorrow = [Link]([Link]() + day_in_seconds)
>>> tomorrow
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=7,
tm_hour=20, tm_min=12, tm_sec=5,
tm_wday=5, tm_yday=67, tm_isdst=0)
Th
is
oc d
um
[Link]([secs])
en
tb
elo
n
No jagta gs to
un p NI
[Link]([secs]) au nilis LK to [Link]([secs]), but it converts a time expressed in seconds
similar
tho kant AN
since the epoch to a struct_time @ in the time. As with [Link]([secs]), if the secs argument is
riz
ed red Tlocal E
omitted, it defaults to [Link](), co whichiff. S HW
returns
pie com AR the current time in seconds since the epoch. The value of
tm_isdst will be 0 or 1 depending on awhether s JA savings time applies.
daylight
llo GT
we AP
d! .
[Link]().tm_isdst
Th
[Link]()
is
do
cu
men
tb
elo
The inverse of [Link]()
n is [Link](), which takes a struct_time and returns the number of
No jagta gs to
seconds since the epoch:
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
>>> lt = [Link]() sa JA
llo GT
we AP
>>> lt d! .
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=6,
tm_hour=14, tm_min=33, tm_sec=32,
tm_wday=4, tm_yday=66, tm_isdst=0)
Th
>>> seconds_since_epoch = [Link](lt)
is
do
cu
>>> seconds_since_epoch
m en
1583523234.0 tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
Times as Strings co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
When comparing or doing any sort of calculations with dates and times, it is necessary to treat them as objects or
numbers; however, when outputting dates in reports, it is more useful to see their human-readable string
representations.
Th
sd i
String Representation
o of Current Local Time
cu
en m
>>> [Link]() tb
elo
'Fri Mar 6 [Link]ja 2020'ng
N g s
[Link]([secs])
[Link]([secs]) is like [Link]([t]), but it takes a time expressed in seconds since the epoch
instead of a struct_time. It returns a date in local time represented as a string. If the secs struct_time
argument is Tomitted, it defaults to [Link](), which returns the current time in seconds since the epoch.
his
do
cu
me
nt
be
>>> str_epoch_offset =[Link](0) # "offset," because it's local time
No ja gta gs to
un p NI
>>> str_epoch_offset au nilka L
tho nt@ KAN
'Wed Dec 31 [Link] 1969' riz re TE
ed SH
co diff.c
pie om WAR
sa JA
>>> str_now = [Link]() llo GT
we AP
d! .
>>> str_now
'Fri Mar 6 [Link] 2020'
Time and
Th Formatted Strings
is
do
cu
men
tb
elo
N jag ngs
[Link](format[,ou ta t])to
na pnilk NIL
uth a K
ori nt@ ANT
ze r
d c ediff ESH
o .co W
The [Link](format[, pt]) ies takes m aA struct_time
R object and returns a formatted string. The “f” in
all JA
“strftime” is for “format.” o we G TA
d! P.
[Link](string[, format])
Th
The [Link](string[, format]) takes a string representing a time and returns a struct_time
is
d
object. The “p” in o“strptime”
cu is for parse.”
me
nt
be
lon
Formatting DirectivesNo jagta gs to
un p NI
au nilka L
Some of the more common nt@ Kdirectives
thoformatting AN 34 are shown in the following list:
riz r e T E
ed SH
co diff.c
pie om WAR
%a – Abbreviated weekday name. sa JA
llo GT
we AP
d! .
%A – Full weekday name.
1. import time
2. Th
is
do
cu
3. m
def start_clock():
en
4. be
print("Starting
t
lo Clock") ng
jag s
5. try: N
6. while True:
7. localtime = [Link]()
8. result = [Link]("%I:%M:%S %p", localtime)
9. print(result)
10. [Link](1)
11. except KeyboardInterrupt:
12. print("Stopping Clock")
Th
is
13. do
cu
14. me
start_clock() n tb
elo
n
No jagta gs to
un p NI
au nilka L
Code Explanation tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
This will output something like the following,
sa printingJa new time every second until the user presses Ctrl+C:
llo AG
we TA
d! P.
Starting Clock
[Link] AM
[Link] AM
[Link] AM
T
shi
[Link] AM doc
um
[Link] AM en
be t
lon
No agta gs to
Stopping Clock j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c WA
pi35 o m
The datetime Module es allo R
JA
GT
we AP
d! .
2. Th
[Link] – a time with hour, minute, second, microsecond, and tzinfo attributes.
is
do
cu
me
3. [Link] nt – a combination of [Link] and [Link].
be
lon
No jagta g–s a
4. [Link] expressing the difference between instances of two [Link],
un pn to duration
a u ilka NILK
[Link], [Link]
ori nt@ ANT objects.
ze re d E S
dc
op [Link] HWA
ies m R
all JA
ow GT
[Link] Objects e d! AP
.
Th
is
oc d
>>> [Link](1776,
u 7, 4)
me
nt
be
[Link](1776, 7, 4)
lon
N jag gs
2. [Link]() – Returns the current local date.
>>> [Link]()
[Link](2020, 1, 31)
3. [Link](secs)
Th – Returns the local date from secs seconds since the epoch:
is
do
cu
me
nt
>>> week_in_seconds be
lon = 24*60*60*7
ja g
N ou g tap s to
>>> [Link](week_in_seconds) # One week after epoch
na
u
n ilka NILK
[Link](1970, t ho 1,nt@ 7) AN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
[Link] Attributes
A [Link] instance includes the following attributes:
• year
Th
is
do
• month cu
men
tb
elo
• day n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
>>> i_day = [Link](1776, l7, low 4) GT
ed AP
>>> i_day.year, i_day.month, i_day.day ! .
(1776, 7, 4)
[Link]
Th Methods
is
do
A [Link] cuinstance includes the following methods:
me
nt
be
lo
N jag ngs
replace() – oReturns
un
tapa new to [Link] instance based on date with the given replacements.
NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
>>> i_day = [Link](1776, co diff.c WA4)
pie om 7, R
sa JA
>>> i_day.replace(year=1826)llow GT
ed AP
[Link](1826, 7, 4) ! .
Th
is
>>> i_day.timetuple()
d oc
me u
time.struct_time(tm_year=1776,
n tm_mon=7, tm_mday=4,
tb
elo
jag ng
N s
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=3, tm_yday=186, tm_isdst=-1)
>>> i_day.weekday()
T his
3 do
cu
men
tb
elo
n
No jagta gs to
ctime() – Returns
un a formatted
p NI date string. Similar to [Link]().
au nilka LK
tho n A
riz t@re NTE
ed d SH
co if
>>> i_day.ctime() pie [Link] WAR
sa JA
'Thu Jul 4 [Link] 1776' llow GT
ed AP
! .
strftime() – Returns a formatted date string. Similar to [Link](format[, t]) with the same
formatting directives.
Th
is >>> i_day.strftime('%A, %B %d, %Y, %I:%M %p')
do
cu
me
'Thursday, July 04, 1776, 12:00 AM'
nt
be
lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
[Link] Objects pie om WAR
sa JA
llo GT
we AP
d
[Link] objects are created with the! [Link]() . method, which takes the following arguments:
hour – defaults to 0.
minute – defaults to 0.
Th
second – isdefaults to 0.
do
cu
me
nt
microsecond – defaults be to 0.
lon
No agta gs to
j
tzinfo – defaults un to None,
p which
NI makes the datetime object “naive,” meaning that it is unaware of
au nilka LK
timezones. It is common tho to nset A
tzinfo
riz t@re NTE to UTC time like this
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
tzinfo=[Link]. d! .
[Link] Attributes
A [Link] instance includes the following attributes:
Th
hour is
do
cu
men
minute tb
elo
jag ng
N s
second
microsecond
replace() – Returns a new [Link] instance based on time with the given replacements.
Th
is
oc d
[Link]
um
e
Objects
nt
be
lon
No jagta gs to
A [Link] un objectp is NaI combination of a [Link] object and a [Link] object.
au nilka LK
t h
There are a number of datetime
ori n AN for creating [Link] objects:
t methods
ze @red TES
dc
op [Link] HWA
ies m R
1. datetime(year, month, day, JA
all hour, minute, second, microsecond, tzinfo) – creates new
ow GT
ed AP
datetime ! .
4. [Link]()
Th – Returns the current UTC date and time.
is
do
cu
5. me
[Link](timestamp) – Returns the local date and time corresponding to timestamp.
nt
be
lon
6. N jag gs
[Link](timestamp) – Returns the UTC date and time corresponding to
timestamp.
8. [Link](date_string, format) – Takes a string representing a date and time and returns
a [Link] object.
Th
is
do
cu
[Link] me Attributes
nt
be
lon
A [Link]
No ja gs includes the following attributes:
ginstance
t t
un apni o NI
au l LK
tho kant AN
r ize @ T
year d c rediff ESH
op . WA
ies com R
month all JA
ow GT
ed AP
! .
day
hour
minute
Th
second is do
cu
men
microsecond tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m
>>> moon_landing = [Link](year=1969,
JA
month=7, day=21,
llo G
hour=2,weminute=56,TAsecond=15,
d! P.
tzinfo=[Link])
>>> moon_landing.year, moon_landing.month, moon_landing.day
(1969, 7, 21)
>>> moon_landing.hour,
T moon_landing.minute, moon_landing.second
s hi
(2, 56, 15) do
c um
en
tb
lon e
>>> moon_landing.microsecond,
ja g moon_landing.tzinfo
No gta st
o
na pnilk NIL
u
(0, [Link])
u a K
tho
AN nt@
riz
red TES ed H
co if
pie [Link] WAR
sa JA
llo GT
[Link] Methods we AP
d! .
A [Link] instance includes the following methods:
[Link]() – Returns a [Link] object with same year, month, and day.
>>> moon_landing.date()
[Link](1969, 7, 21)
Th
is
do
cu
en m
tb
[Link]() e–loReturns
n a [Link] object with same hour, minute, second, and microsecond.
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz
>>> moon_landing.time() red TES
ed
[Link](2, 56, 15)
c op [Link] HWA
ies m R
all JA
ow GT
ed AP
! .
[Link]() – Returns a struct_time representing the local time.
>>> moon_landing.timetuple()
time.struct_time(tm_year=1969, tm_mon=7, tm_mday=21,
Th
istm_hour=2, tm_min=56, tm_sec=15,
do
cu
me
tm_wday=0, tm_yday=202, tm_isdst=-1)
nt
be
lon
No jagta gs to
un p NI
au nilka L
[Link]() tho nt@ –KAReturns
N a struct_time representing the UTC time.
riz red TES
ed H
co if
pie [Link] WAR
sa JA
>>> moon_landing.utctimetuple() llo GT
we AP
d! .
time.struct_time(tm_year=1969, tm_mon=7, tm_mday=21,
tm_hour=2, tm_min=56, tm_sec=15,
tm_wday=0, tm_yday=202, tm_isdst=0)
Th
[Link]() – Returns a timestamp corresponding to the datetime.
is
do
cu
me
nt
>>> moon_landing.timestamp()
be
lon
-14159025.0 No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co [Link] integer
[Link]() – Returns pie om WAR representing the day of the week.
sa JA
llo GT
we AP
d! .
>>> moon_landing.weekday()
0
2. Write an is_summer() function that takes one argument: a [Link] object that defaults to the
Th
is The function should return True if the date is between June 20 and September 22 of the year,
current time.
do
cu
and False otherwise. You will need to construct dates marking the start of summer and the start of fall. To do
me
nt
b
so, you should make euse lo of the year of the passed-in [Link] object. For example, if the
jag ngs
Nois in
passed in date 2025,
t you
t must check if the date is between June 20, 2025 and September 22, 2025.
un apni o NI
au lka L
tho nt@ KAN
3. r
In the main() function, izmake Tto is_summer() and then print “You should wear white pants.” if it is
ed arecall
dif ESH
c f WifA it isn’t summer.
summer or “You should wearoblack pie .pants.”
co
sa m R
JA
llo GT
we APuse of the ternary operator (see page 165) in the
4. There are many ways to do this. Our solution d! makes .
main() function.
Solution: date-time/Solutions/pant_color.py
Th
is
do
1. cu
from datetime
m import datetime
en
2. tb
elo
ja ng
3. N g tap s to
def is_summer(the_date=[Link]()):
ou
n n NI
4. uth ilof
# Get the ayear ka the LK passed-in [Link] object
ori n t@ ANT
z ed r e ES
co diff.c
5. year = the_date.year HW
pie o AR
6. sa m JA
llo
7. # Create [Link] we objectsGfor
TA starts of seasons
d! P.
8. summer_start = datetime(year, 6, 20)
9. fall_start = datetime(year, 9, 22)
10.
11. # Return true if passed-in date is between starts of seasons
12. Th
return (summer_start < the_date < fall_start)
is
do
13. cu
men
14. def main(): tb
lo e
15. jag noperator
# Use Nternary gs to assign pant color
16. pant_color = 'white' if is_summer() else 'black'
17. print(f'You should wear {pant_color} pants.')
18.
19. main()
[Link]
Th
is Objects
do
cu
A [Link]
nt object expresses a duration – the time between two date, time, or datetime objects.
be
lon
No ja gta gs to
un p NI
au nilka LK
tho
[Link] objects
riz @ A
ntcan be…N
ed red TES
co if H
pie [Link] WAR
sa JA
llo GT
we AP
d! .
Added (t1 + t2). Result: a new [Link] object.
seconds
microseconds
Th
is
do
cu
men
tb
elo
ja ng
>>> Nou g tap s to
now = [Link]()
na n N
>>> uth ilkan ILKA
starttime = [Link](hour=8, minute=30, second=0, microsecond=0)
ori t N
ze @red TES
dc
op [Link] HWA
>>> endtime = [Link](hour=8, minute=48, second=23, microsecond=0)
>>> racetime = endtime - starttime ies m R
all JA
ow GT
>>> racetime ed AP
! .
[Link](seconds=1103)
>>> [Link], [Link], [Link]
(0, 1103, 0)
Th
is
do
cu
me
[Link].total_seconds() Method
nt
be
lo
N jag ngs
A [Link] instance includes only one method: total_seconds(), which returns the total number
of seconds in the duration (with microsecond accuracy).
>>> racetime.total_seconds()
1103.0
Th
is
do
cu
me
The Time Delta Between nt Dates
be
lon
ja
No delta gs
gta between
To determine the time two dates, simply subtract one from the other:
un pn to NI
au ilka LK
tho n A
riz t@re NTE
ed d SH
co if
>>> start = [Link](year=1861, pie [Link] WAR month=4, day=12)
sa JA
llo GT
>>> end = [Link](year=1865, we AP day=9)
month=4,
d! .
>>> delta = end - start
>>> [Link]
1458
Th
is
do
cu
me
nt
Exercise 28: beReport on Departure Times
lo n
No jagta gs to
un pn NI
au il LK
tho kant
riz @ ANT
r ES
45 to 90 minutes ed c ediff
op .co HWA
ies m R
all JA
ow GT
ed AP
! .
In this exercise, you will create a small report on departure times from July, 1980. All the data is in a text file (date-
time/data/[Link]). Some of the data is shown below:
Th
is
1. do Actual
*Scheduledc um
2. en AM 07/01/1980 4:00 AM
07/01/1980 2:40
t be
l
on 07/01/1980 3:00 AM
No jagta gs to
3. 07/01/1980 3:00 AM
un AMpn 07/01/1980
4. 07/01/1980 4:40
a ilk NIL
u
4:40 AM
a K
tho nt@ AN
5. 07/01/1980 5:30 AM riz07/01/1980
red TE5:30 AM
ed
c o iff. SHW
6. 07/01/1980 6:00 AM 07/01/1980pie c om6:01A AM
sa R
AG J
-------Lines 7 through 1969 lloOmitted-------
w T
ed AP
!
1970. 07/25/1980 7:00 PM 07/25/1980 7:09 PM .
Things to note:
The main() and get_departures() functions are complete. Your task is to complete the
get_departure() function.
Th
is
do
cu
me
1. Open date-time/Exercises/departure_report.py in your editor.
nt
be
lon
2. Review the main()
N jagand gget_departures()
s functions.
3. Your first job is to write the get_departure() function:
A. The first line is a header and begins with an asterisk (*). Return None for that line.
D. Convert the planned departure time to a datetime and assign the result to
date_planned.
Th
is
do
c
E. For thoseumlinesen that have an actual departure time, convert the actual departure time to a datetime
t
and assign thebresult elo to date_actual. For lines that don’t have an actual departure date, assign None
ja ng
N
to date_actual.
ou g ta s to
na pnilk NIL
uth an KA
t
ori date_planned N
F. Return a tuple with ze @red TES and date_actual. This line is already written.
dc iff HW
op .
ies com AR
4. Study the main() function. See how all it makes JuseAG of the left_ontime(), left_early(), left_late(),
ow TA
left_next_day(), and did_not_run() e d P. The left_ontime() function is already written.
functions.
!
Write the other four functions. They should all return a boolean value.
Solution: date-time/Solutions/departure_report.py
Th
is
do
-------Lines 1 cthrough
um 12 Omitted-------
en
tb
13. el
def get_departure(line):
o
ng
No jaagtatuple s containing two datetime objects."""
pn to NI
14. """Return
un i
au l LK
15. th kan o t@ AN
riz re TE
ed SH
16. if line[0] == '*': co diff.c
pie om WAR
17. return None sa J AG
llo
18. we TA
d! P.
19. departure = [Link]('\t')
20. planned = departure[0]
21. actual = departure[1]
22.
23. Th
date_planned = [Link](planned, '%m/%d/%Y %I:%M %p')
is
do
24. cu
me
25. nt
if actual: be
lon
26. ja
date_actual
N g gs = [Link](actual, '%m/%d/%Y %I:%M %p')
27. else: # Date doesn't exist
28. date_actual = None
29.
30. return (date_planned, date_actual)
31.
32. def left_ontime(departure):
33. """Return True if left ontime. False, otherwise."""
Th
is
34. do
planned = departure[0]
u c
35. actual m= edeparture[1]
nt
be
36. if not actual: lon
No gtaja gs
37. return pn to NI
un False
uth aa i KA lk L
ori== nplanned
t N
ze @red TES
38. return actual
dc
39. op [Link] HWA
ies m R
40. def left_early(departure): allo JA
G w T
ed AP
41. """Return True if left early. .
! False, otherwise."""
42. planned = departure[0]
43. actual = departure[1]
44. if not actual:
45. return False
Thisactual < planned:
46. if
do
um c
47. print('Early:',
e departure)
nt
48. be < planned
return actual
lo n
49. No jagta gs to
un pn NI
au il LK
tho kant
50. def left_late(departure):
riz @ ANT
re
ed left ES
51. """Return True if co difflate. H False, otherwise."""
pie . c om WAR
52. planned = departure[0]a s JA
llo GT
we AP
53. actual = departure[1] d! .
54. if not actual:
55. return False
56. return actual > planned
57.
58. Th
def left_next_day(departure):
is
do
59. """Returncu
m True if departed next day. False, otherwise."""
en
60. planned = tdeparture[0]
be
lo
61. jag ngs
actualNo= departure[1]
t t
un apni o NI
62. au
if not actual: lka LK
th n ANor t@
63. return Falsered TES
ize
d
co iff.c HW
p o
return [Link] > [Link] AR
64. sa m JA
llo GT
65. we AP
d! .
66. def did_not_run(departure):
67. """Return True if did not depart. False, otherwise."""
68. return not departure[1]
-------Lines 69 through 85 Omitted-------
Th
is
do
cu
Code Explanation men
tb
elo
ja ng
N g s
The result of running this file is shown below:
Total Departures: 2481
Ontime Departures: 1207
Early Departures: 0
Late Departures: 1260
Next Day Departures: 2
Cancelled Trips: 14
Th
is
do
cu
men
tb
Conclusion elo
n
No jagta gs to
p
un learned NI
In this lesson, you have au nilkato work L with the time and datetime modules.
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
30. The [Link] image is used under the
terms of Public Domain
([Link]
.
Th
is
do
31. The time of thecu epoch varies across computing systems, but in Python it is pretty much guaranteed to by
me
nt
January 1, 1970. For bea
lon
No agta gs to
j
un seepn[Link]
discussion on this, il NI
au LK
tho kant
platform. riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d ! .
32. Documentation on the time module: [Link]
33. [Link]
Th
is
do
cu
34. Documentation mon
en date and time formatting directives is available at
tb
elo
[Link]
n
No agta gs to
j
u na p n N
[Link]?highlight=strptime#strftime-and-strptime-format-codes.
uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
ies com AR
a l JA
35. Documentation on the datetime module: low GT
[Link]
ed AP
! .
Th
is
do
cu
men
tb
elo
jag ng
N s