a) Take a few minutes to browse the modules in the Python module index.
b) Import the module datetime
, a module that provides functionality for working with dates. We will now use it to calculate your age in days, hours and seconds repsectively.
Write a function that accepts a birth date of a person:
> calculate_age(1999, 1, 2, hour=12, minute=2, second=33)
You are 7263 days old
You are 174313 hours old
You are 627527127 seconds old
Year, month and date is required, the other values are optional. The default values of hour, minute and second should be 0.
The function should print the following:
The datetime
module will provide you with the number of days and seconds. You will need to calculate the number of hours on your own.
Hints:
Use the datetime Object
to solve the exercise.
Find out how to make a datetime
object representing the current time.
Find out how to make a datetime
object representing a given date and time (the birth date).
Look at the supported operations for this type to find how you can get the difference between two objects of type datetime
.
You will get difference represented as an object (a timedelta
).
Use .days
and .total_seconds()
to get the number of days and seconds.
c) Test your functions by giving it different input and make sure that they give the expected output.
d) Go back to the previous IMDB exercise, where you defined the pick_movie()
function.
Use the module random
to make the movie picker less predictable: instead of always returning the first matching movie from the file, return a randomly picked movie (which still matches the user's criteria).
import datetime
def calculate_age(year, month, day, hour=0, minute=0, second=0):
""" Calculate the number of days, hours and seconds that have passed since a given date """
# create a date object for current time
now = datetime.datetime.now()
# create a date object for the giventime
born = datetime.datetime(year, month, day, hour, minute, second)
# compare them
diff = now - born
# get the number of days that have passed
days = diff.days
# get the number of seconds
tot_seconds = int(diff.total_seconds())
# convert into hours using floor division
hours = tot_seconds // 3600
print('You are ' + str(days) + ' days old')
print('You are ' + str(hours) + ' hours old')
print('You are ' + str(tot_seconds) + ' seconds old')
calculate_age(1984, 3, 19)
You are 12650 days old You are 303615 hours old You are 1093014139 seconds old
import random
imdb = "../../downloads/250.imdb"
def pick_movie_b_ii(year=None, genre=None, rating_min=None, rating_max=None):
# read all lines and keep them in memory
lines = open(imdb).readlines()
# use random to shuffle the lines (put them in random order)
random.shuffle(lines)
# now go through the lines and return the first one that fits
for line in lines:
if line.startswith('#'):
continue
fields = line.split('|')
# Remeber to type cast to float
rating = float(fields[1].strip())
title = fields[-1].strip()
m_year = fields[2].strip()
genres = fields[-2].strip().split(',')
# Go through criterias
ok_year = not year or m_year == year
ok_genre = not genre or genre in genres
ok_min = not rating_min or rating_min <= rating
ok_max = not rating_max or rating_max >= rating
if ok_year and ok_genre and ok_min and ok_max:
# All criterias ok, print the movie and break the loop
print(title)
break
pick_movie_b_ii(year="2001")
A Beautiful Mind
pick_movie_b_ii(year="2001")
Spirited Away