0% found this document useful (0 votes)
5 views

Datetime Activities

Uploaded by

1yangeth3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Datetime Activities

Uploaded by

1yangeth3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Python with AI Level 2

Date Time Activities

Contents
Date Time Activities ....................................................................................................................................................................................................... 1
Activity 1 Know your time! ........................................................................................................................................................................................ 2
Sample Expected Result ......................................................................................................................................................................................... 2
What to do ............................................................................................................................................................................................................. 2
Activity 2 Display Date and time ................................................................................................................................................................................ 3
Sample Expected Result ......................................................................................................................................................................................... 4
What to do ............................................................................................................................................................................................................. 4
Duration ......................................................................................................................................................................................................................... 5
Activity 3 Add 5 Seconds ............................................................................................................................................................................................ 5
Sample Expected Result ......................................................................................................................................................................................... 5
What to do ............................................................................................................................................................................................................. 5
Activity 4 Previous, Present and Future ..................................................................................................................................................................... 5
Sample Expected Result ......................................................................................................................................................................................... 6
What to do ............................................................................................................................................................................................................. 6
Activity 5 How many days until the National Day? .................................................................................................................................................... 7
What to do ............................................................................................................................................................................................................. 7
Activity 6 Order & Shipping........................................................................................................................................................................................ 8
Sample Expected Result ......................................................................................................................................................................................... 8
What to do ............................................................................................................................................................................................................. 8
Challenge 1 (Optional) - How fast is your computer? .............................................................................................................................................. 9

1
Python with AI Level 2

What to do ............................................................................................................................................................................................................. 9
Challenge 2 (Optional) Count Down Timer .............................................................................................................................................................. 10
Sample Expected Result ....................................................................................................................................................................................... 11
What to do ........................................................................................................................................................................................................... 11

Activity 1 Know your time!


Write a Python program to display the various date time formats.
a) Current date and time
b) Current year
c) Month of year
d) Day of the month
e) Current hour
f) Current minute
g) Weekday of the week

Sample Expected Result

What to do
1. Open Visual Studio Code, create a Python program file called datetime-ex1.py.
2. import the datetime module.

2
Python with AI Level 2

import datetime

3. Then, add the following code:


# Current datetime
now = datetime.datetime.now()

print(now)
print(f"Current year is {now.year}")
print(f"Current month is {now.month}")
print(f"Current hour is {now.hour}")
print(f"Current minute is {now.minute}")
print(f"Weekday of the week is {now.weekday()}")
print(f"Day of the month is {now.day}")

4. Save all changes and run the program. You should get similar result above.
5. Now change the follow statement
now = datetime.datetime.now()

To
now = datetime.datetime(2020,9,12)

6. Run the program again and observe the result.

Activity 2 Display Date and time


In this activity, you will format the date and time in different ways.

Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%d Day of the month 01-31 31

%b Month name, short version Dec

3
Python with AI Level 2

%B Month name, long version December

%m Month as a number, 01-12 12

%Y Year, full version 2020

%H Hour 00-23 17

%I Hour 00-12 05

Sample Expected Result

What to do
Open Visual Studio Code, create a Python program file called datetime-ex2.py. Add the following code:

import datetime

#display date and time


now = datetime.datetime.now()
print("format date and time")
print(now)
print(now.strftime("%A, %B %d, %Y"))
print(now.strftime("%a, %b %d, %Y"))
print(now.strftime("%a, %b %d"))
print(now.strftime("%m/%d/%y"))

Save all changes and run the program.

4
Python with AI Level 2

Duration
Activity 3 Add 5 Seconds
Write a Python program to add 5 seconds to the current time. Display both the current and the new time. Date should not be included.

Sample Expected Result

What to do
1. Open Visual Studio Code, create a Python program file called add-seconds.py. Import the required module:

import datetime

2. Then, get the current date time.

now = datetime.datetime.now()

3. Create a duration object to represent 5 seconds:

duration = datetime.timedelta(seconds=5)

4. Calcuate the new time:

new = now + duration

5. Display only time part:

print("The current time is", now.strftime("%I:%M:%S"))


print("The new time is ",new.strftime("%I:%M:%S"))

6. Save all the changes, and run the program.

Activity 4 Previous, Present and Future


Write a Python program to print dates of yesterday, today, tomorrow.

5
Python with AI Level 2

Sample Expected Result

Today is 2022-01-09
Yesterday is 2022-01-08
Tomorrow is 2022-01-10

Please note, the actual dates will be different than the sample.

What to do
1. Open Visual Studio Code, create a Python program file called today-yesterday-tomrrow.py. Import required module:

# print dates of yesterday, today, tomorrow.


import datetime

2. Get current date only


today = datetime.date.today()

3. Create a duration object to represent 1 day duration


day = datetime.timedelta(days=1)

4. Calculate the dates of yesterday and tomorrow

yesterday = today - day


tomorrow = today + day

5. Display

print(f"Today is {today}")
print(f"Yesterday is {yesterday}")
print(f"Tomorrow is {tomorrow}")

6. Save all changes and run the program. Obverse the result.

6
Python with AI Level 2

7. After you finished the previous steps, change


today = datetime.date.today()

to:

today = datetime.date(2020,12,31)

8. Save all changes and run the program. Obverse the result.

Activity 5 How many days until the National Day?


You will track how many days until the next National Day. You will need to consider if the National day of this year has passed or not. If it passed,
the National Day will be in next year.

What to do
1. In Visual Studio Code, create a file called national-day.py. Add the following code:
# you can change the month and day to reflect your National day.
month = 7
day = 1

2. Then, you need to get the current day and the National day in this year.

now = datetime.datetime.now()
nationalday = datetime.datetime(now.year,month,day)

3. Next, check if the National Day has passed. If so, the next National Day is next year.

if now > nationalday:


#The national day has passed. The next National day is next year.
nationalday = datetime.datetime(now.year+1,month,day)

4. Now you need to get the duration between now and the National Day.

td = nationalday - now
print(f"There are {td.days} days until the National Day.")

7
Python with AI Level 2

5. Save all changes, and run the program.

Activity 6 Order & Shipping


Assume you are part of a team to write an online shopping program. Your task is to track order placed date, delivery date and return window.
The estimated delivery day depends on delivery options. That is

• Regular 4 days
• Express 2 days

The return windows is a 30 days starting from product delivered day.

You will write a program to allow the user select the delivery options, and display the estimated delivery day, and return window.

Sample Expected Result

What to do
1. In Visual Studio Code, create a file called shipping.py. Import the required module:
import datetime

2. Create variable to store display message:


display = """
-------------------------------
Please select delivery option:
r for Regular 4 days (Free)
e for Express 2 days ($9.99)

8
Python with AI Level 2

-------------------------------
"""
3. Create a dictionary variable to store the delivery schedule.
deliver_schedule = {
"r": 4,
"e":2
}
4. Ask the user to select delivery method
delivery_method = input(display).lower()
5. Get the delivery days from the dictionary object.
delivery_days = deliver_schedule[delivery_method]

6. Get order placed date which is the current date.


now = datetime.datetime.now()
7. Calculate estimated delivery date and return window.
estimated_delivery_date = now + datetime.timedelta(days=delivery_days)
return_window = estimated_delivery_date + datetime.timedelta(days=30)
8. Display the order date, estimated delivery date and return window.
print(f"Your order has been placed at {now.strftime('%b %d,%Y %I:%M%p')}")
print(f"Estimated delivery date is {estimated_delivery_date.strftime('%b %d,%Y')}")
print(f"The retun windows is by {return_window.strftime('%b %d,%Y')}")

9. Save all changes and run the program.

Challenge 1 (Optional) - How fast is your computer?


Have you ever wondering how fast is your computer? Let’s check it out. You will write code to have your computer to do many times of
multiplication, saying 5,000,000 times. You will measure how long it takes to finish. Before you measure, guess how long. Write it down.

What to do
1. Open Visual Studio Code, create a Python file called how-fast.py.
2. You will use datetime module to measure time, so

9
Python with AI Level 2

import datetime

3. Then you define two variables. You will use the variable to control number of time you want to multiplications.
max_i = 1000
max_j = 5000

4. Record the start time before you start to do multiplication,


start = datetime.datetime.now()

5. Now you write two loops to have your computer to do multiplications.


for i in range(max_i):
for j in range(max_j):
a = i * j
6. Once the loops finished, you record the finish time
end = datetime.datetime.now()

7. Then you can calculate the duration from start time to finish time.
duration = end – start

8. Finally, you can display the result.


print(f"You computer took {duration} to do {max_i * max_j} times of multiplicatoins.")

9. Write down the time, and compare it to your guess earlier. Are they close?

Challenge 2 (Optional) Count Down Timer


You will see how to create a countdown in Python. The code will take input from the user regarding the length of the countdown in seconds.
After that, a countdown will begin on the screen of the format ‘minutes:seconds’. You will be using the time module for this program.

10
Python with AI Level 2

You will be using the time module. Then we will be using the sleep() function. To use this function you will first import the time module into our
code. time.sleep(n) function makes the code wait for ‘n’ seconds. So, for this countdown you will be using time.sleep(1) as we want the code to
wait for 1 second in between two successive prints.

Sample Expected Result

What to do
1. You will import the time module.
import time

2. You will then ask the user to input the length of countdown in seconds.
t = input("Enter the time in seconds: ")

3. This value is sent as a parameter ‘t’ to the user- defined function countdown(). Any variable read using input function is a string. So, we type
convert this parameter to ‘int’ as it is of string type.
countdown(int(t))

4. In this function a while loop runs till time becomes 0.


def countdown(t):
while t:

The countdown function should be right after the import statement.

5. Within the while loop body, you then use divmod() to calculate the number of minutes and seconds.
mins, secs = divmod(t, 60)

11
Python with AI Level 2

divmod will return t//60 to mins, and t%60 to secs. The first one if the quotient, the second one is reminder.

6. Then you will print the minutes and seconds on the screen using the variable timeformat.
timer = '{:02d}:{:02d}'.format(mins, secs)’

7. Using end = ‘\r’ we force the cursor to go back to the start of the screen (carriage return), so that the next line printed will overwrite the
previous one.
print(timer, end="\r")

8. time.sleep() is used to make the code wait for one sec.


time.sleep(1)

9. You then decrement time so that the while loop can converge.
t -= 1

10. After the completion of the loop we will print “Blast Off!!!” to signify the end of the countdown.
print('Blast Off!!!')

This should be outside of the while loop body.


11. Save all changes and run the program.

12

You might also like