Page 318 - CTS - CSA TP - Volume 2
P. 318

COMPUTER SOFTWARE APPLICATION - CITS




           Output:








           TASK 4: Manipulating Dates and Times with the datetime Module
           Code:

           from datetime import datetime, timedelta
           current_time = datetime.now()
           one_week_later = current_time + timedelta(weeks=1)
           print(f”Current time: {current_time}”)

           print(f”One week later: {one_week_later}”)
           Explanation:
           1  Importing the datetime Module:
           •  from datetime import datetime, timedelta: This line imports the datetime module, which provides classes for
              working with dates and times, and the timedelta class, which represents the difference between two dates or
              times.
           2  Getting the Current Time:

           •  current_time = datetime.now(): This line gets the current date and time and assigns it to the variable current_
              time using the now() method of the datetime class.
           3  Calculating One Week Later:

           •  one_week_later = current_time + timedelta(weeks=1): This line adds one week (7 days) to the current time
              using the timedelta class. The result is stored in the variable one_week_later.
           4  Displaying the Results:
           •  print(f”Current time: {current_time}”): This line prints the current time to the console using an f-string.

           •  print(f”One week later: {one_week_later}”): This line prints the calculated time one week later to the console
              using an f-string.
           Output:









           Related Exercises
           1  Write a Python program that generates and prints a random number between 1 and 50 using the random
              module
           2  Create a program that takes user input for a temperature in Celsius and converts it to Fahrenheit using the
              appropriate formula. Utilize the math module for mathematical operations.
           3  Develop a program that prompts the user to enter a specific date and then calculates and displays the date
              and time exactly one month later using the datetime module.
           4  Build a Python program that takes an angle in degrees as input and calculates and prints the sine, cosine, and
              tangent values using functions from the math module.
           5  Write a program that creates a new text file and writes the current date and time (timestamp) to it. Utilize the
              datetime module for timestamp generation.



                                                           303
                             CITS : IT & ITES - Computer Software Application - Exercise 137
   313   314   315   316   317   318   319   320