Quick Timestamp with ctime()
The simplest way to display a readable date/time is ctime() from the time module:
from time import ctime
print("Current time:", ctime())
It prints a full timestamp; the exact format can vary by system.
Date / Time Task 1 – Dentist Surgery
Print a friendly greeting that includes the current date/time.
from time import ctime
print("Welcome to Greenvale Dentist Surgery, it is currently:", ctime())
Custom Date & Time with strftime()
Use strftime() to format the output exactly how you want (HH:MM:SS, day names, etc.).
from time import strftime
print("The current time is", strftime("%H:%M:%S"))
Extract specific parts too:
from time import strftime
day = strftime("%A")
month = strftime("%B")
year = strftime("%Y")
print("Today is", day, month, year)
Date / Time Task 2 – Calendar App
Ask the user what they want to see and format appropriately.
from time import strftime
choice = input("Type TIME for the current time, DATE for the current date, or OTHER for additional info: ").upper()
if choice == "TIME":
print("The current time is", strftime("%H:%M:%S"))
elif choice == "DATE":
print("Today's date is", strftime("%A %B %d, %Y"))
else:
print("Did you know today is day number", strftime("%j"), "of the year?")
Days Between Dates
Use datetime.date to subtract one date from another:
from datetime import date
date1 = date(2021, 9, 15)
date2 = date(2022, 1, 20)
difference = date2 - date1
print("There are", difference.days, "days between", date1, "and", date2)
Today’s Date
Build a date object for today using values from strftime():
from datetime import date
from time import strftime
this_year = int(strftime("%Y"))
this_month = int(strftime("%m"))
this_day = int(strftime("%d"))
todays_date = date(this_year, this_month, this_day)
print("The date today is", todays_date)
Input a Date
Let the user enter a date, then print it in standard ISO format (YYYY-MM-DD):
from datetime import date
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
day = int(input("Enter a day: "))
chosen_date = date(year, month, day)
print("The chosen date is", chosen_date)
Date / Time Task 3 – Days Alive
Calculate how many days the user has been alive by subtracting their birth date from today.
from datetime import date
from time import strftime
this_year = int(strftime("%Y"))
this_month = int(strftime("%m"))
this_day = int(strftime("%d"))
todays_date = date(this_year, this_month, this_day)
birth_year = int(input("Enter your birth year: "))
birth_month = int(input("Enter your birth month: "))
birth_day = int(input("Enter your birth day: "))
birth_date = date(birth_year, birth_month, birth_day)
days_alive = (todays_date - birth_date).days
print("You have been alive for", days_alive, "days!")