19KEEPING TIME, SCHEDULING TASKS, AND LAUNCHING PROGRAMS

Clocks and calendars aren’t as straightforward as text and numeric data, but Python’s time and datetime modules make timestamps and date information easy to handle. Your computer’s clock can schedule programs to run code at some specified time and date or at regular intervals. By learning to leverage these features, you can make use of all the software available on your computer.

A simple drawing of a light bulb. LEARNING OBJECTIVES

  • Understand how Python programs can access your computer’s system clock.
  • Use the datetime module to perform time- and calendar-related operations.
  • Learn how the datetime and timedelta data types represent durations and moments in time.
  • Run other programs from your Python script, either immediately or on a schedule.

A grey circle with a white question mark at the center Practice Questions

These questions test your ability to work with time and calendar data, as well as your ability to schedule your Python programs to run other apps on your computer.

The time Module

Your computer’s system clock is set to a specific date, time, and time zone. The built-in time module allows your Python programs to read the system clock and retrieve the current time.

  1. 1. What time zone is the Unix epoch timestamp in?

  2. 2. What function returns a string of the current time, like 'Tue Mar 17 11:05:45 2026'?

  3. 3. What function returns a float of the current time, like 1773813875.3518236?

  4. 4. Say you’ve run import time. What is time? What is time.time()?

  5. 5. What does the expression time.time() + 10 evaluate to?

  6. 6. What does the expression time.ctime(time.time() - 10) evaluate to?

  7. 7. What is profiling? What does it mean to profile code?

  8. 8. How do you make your program pause its execution for one-half of a second?

  9. 9. Say you decide a timestamp like 1773813875.3518236 has too many digits after the decimal point. What code returns the current time rounded to the nearest second?

The datetime Module

The time module is useful for getting a Unix epoch timestamp to work with. But if you want to display a date in a more convenient format or do arithmetic with dates (for example, figuring out what date was 205 days ago or what date is 123 days from now), you should use the datetime module.

  1. 10. Say you’ve run import datetime. What is wrong with the code datetime.now()?

  2. 11. If you run current_time = datetime.datetime.now(), how can you get an integer of the current year?

  3. 12. What date and time does the datetime object from this expression represent: datetime.datetime.fromtimestamp(0)? (Assume you’re in the UTC time zone.)

  4. 13. Objects of what data type represent a moment in time?

  5. 14. Objects of what data type represent a duration of time?

  6. 15. The datetime.timedelta() function can have keyword arguments like datetime.timedelta(days=11, hours=10, minutes=9, seconds=8). Why can’t you specify the number of months or years?

  7. 16. What code creates a timedelta object that represents 1,000 days?

  8. 17. Reuse the code from the previous question in an expression that evaluates to a timedelta object that represents 2,000 days.

  9. 18. If you add a datetime.datetime object to a datetime.timedelta object, what is the data type of the evaluated result?

  10. 19. If you add a datetime.timedelta object to a datetime.timedelta object, what is the data type of the evaluated result?

  11. 20. Assume you run from datetime import timedelta. What does the expression timedelta(seconds=15) - timedelta(seconds=5) == timedelta(seconds=10) evaluate to?

  12. 21. Assume you run from datetime import timedelta. Does timedelta(seconds=15) + 5 == timedelta(seconds=20) evaluate to True?

  13. 22. What does datetime.timedelta(seconds=60) == datetime.timedelta(minutes=1) evaluate to?

  14. 23. What does the “f” in strftime() stand for?

  15. 24. What does the “p” in strptime() stand for?

  16. 25. Which function takes a date and time as a human-readable string, along with a string to parse it, and then returns a datetime.datetime object: strftime() or strptime()?

  17. 26. Which function returns a date and time as a human-readable string: strftime() or strptime()?

  18. 27. Does datetime.datetime.strptime('26', '%y') evaluate to a datetime object with the year 1926 or 2026?

  19. 28. Does datetime.datetime.strptime('76', '%y') evaluate to a datetime object with the year 1976 or 2076?

  20. 29. What datetime object does datetime.datetime.strptime("October of '26", "%B of '%y") evaluate to?

  21. 30. What does the expression datetime.timedelta(days=0, hours=0, minutes=1, seconds=5).total_seconds() evaluate to?

Launching Other Programs from Python

Your Python program can start other programs on your computer. If you want to start an external program from your Python script, pass the program’s filename to subprocess.run(). Multiple open instances of an application are separate processes of the same program.

  1. 31. What is the difference between a process and a program?

  2. 32. What is the data type of the argument passed to subprocess.run()?

  3. 33. Why doesn’t subprocess.run(['/System/Applications/Calculator.app']) run the calculator app on macOS?

  4. 34. How is the subprocess.Popen() function different from the subprocess.run() function?

  5. 35. The subprocess.run() and subprocess.Popen() functions return Popen objects. What does the poll() method of Popen objects return if the launched program is still running at the time of the method call?

  6. 36. What does the poll() method of Popen objects return if the launched program has quit?

  7. 37. If a program has quit without errors, what is its exit code?

  8. 38. What happens when you call a Popen object’s kill() method?

  9. 39. What happens when you call a Popen object’s wait() method?

  10. 40. Write the code to open a hello.txt file using the default application for opening .txt files on Windows.

  11. 41. Write the code to open a hello.txt file using the default application for opening .txt files on macOS and Linux.

  12. 42. Write the code to run a Python script named spam.py.

A simple drawing of a sharpened pencil. Practice Projects

In the following projects, you’ll create an alarm, an image opener, and a holiday reminder.

Alarm with Sound

Write a function called alarm_with_audio(alarm_time, audio_filename) whose first argument is a datetime.datetime object that sets an alarm and whose second argument is a string representing an audio filename to play at that time. The function should return only after playing the audio file at the time of the alarm.

This function has a few special requirements. It should check whether the audio file exists when first called and should raise an exception if it doesn’t. After all, you don’t want the function to pause for hours and then fail to play any sound because the audio filename had a typo. To know when the time of the alarm has arrived, the function should enter a loop that repeatedly calls time.sleep(0.1) (to add a slight pause and avoid hogging the CPU) until one second after the alarm time.

To play the audio file, call subprocess.run() to open the file with the operating system’s default application for audio files. Keep in mind that you won’t hear the audio if your volume is muted.

Save this program in a file named alarmWithSound.py.

Image Opener

Write a function named open_images_by_name(image_folder, name_match) that takes two string arguments. The first string is the name of a folder containing images, and the second string is a search term with which to perform a case-insensitive match. If image_folder is r'C:\memes' and name_match is 'cat', the function should search C:\memes and open any image filenames that contain the word cat, such as cat-snuggle.png or muffin_cat.jpg.

For the purposes of this exercise, an image file is any file that ends with .png, .jpg, or .webp. Use subprocess.run() to open the image with the operating system’s default application for image files.

My well-organized memes folder contains 3,300 carefully named image files, so I find this program quite useful for seeing all images of a certain topic. It may or may not be as useful to others.

Save this function in a file named openImagesByName.py.

“Next Holiday” Reporter

Here is a dictionary of dates formatted as strings, along with the name of the holiday on that date: {'October 31': 'Halloween', 'February 14': 'Valentine's Day', 'April 1': 'April Fool's Day', 'May 1': 'May Day', 'May 5': 'Cinco de Mayo'}.

Write a function named next_holiday(from_date) that accepts a datetime.datetime object and returns either the holiday on that day or the next upcoming holiday. For example, if you called next_holiday(datetime.datetime(2028, 10, 31, 0, 0, 0)), the function should return 'Halloween' because October 31, 2028, is on Halloween. On the other hand, if you call next_holiday(datetime.date(3000, 1, 1, 0, 0, 0)), the function should return 'Valentine's Day' because that is the first holiday after January 1, 3000, in our dictionary of holidays.

Hint: from_date.strftime('%B') will return the name of the month as a string, like 'November' or 'May', and from_date.strftime('%d') will return the day of the month, like 01 or 31. The day will always be two digits long, with a leading zero if necessary, which doesn’t match the keys in our dictionary of holidays. You’ll have to strip out this leading zero by calling the lstrip() string method.

Save this program in a file named nextHoliday.py.