Exercise
Working With Date And Time
Objective
Develop a Python program that works with date and time. The program should allow the user to input a date and time, and then display the current date and time, as well as the difference between the two. Implement functionality to format the date and time in various formats, and include error handling for invalid date or time inputs.
Example Python Exercise
Show Python Code
from datetime import datetime
def get_user_input():
"""Prompt the user for a date and time input."""
date_str = input("Enter a date and time (format: YYYY-MM-DD HH:MM:SS): ")
# Try to parse the date string
try:
user_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
return user_date
except ValueError:
print("Invalid date or time format. Please use the format: YYYY-MM-DD HH:MM:SS")
return None
def calculate_time_difference(user_date):
"""Calculate the difference between the current date and time and the user input."""
current_date = datetime.now()
time_difference = current_date - user_date
return current_date, time_difference
def format_datetime(datetime_object):
"""Return a string with the formatted date and time."""
# Various formats
formatted = {
"default": datetime_object.strftime('%Y-%m-%d %H:%M:%S'),
"short": datetime_object.strftime('%m/%d/%Y'),
"long": datetime_object.strftime('%A, %B %d, %Y %I:%M:%S %p'),
"iso": datetime_object.isoformat()
}
return formatted
def main():
# Get user input
user_date = get_user_input()
if user_date is None:
return
# Calculate the current date and time
current_date, time_difference = calculate_time_difference(user_date)
# Format and display the current date and time
formatted_current = format_datetime(current_date)
# Display the user input date and time
formatted_user_date = format_datetime(user_date)
# Output the formatted results
print("\nCurrent Date and Time (Formatted):")
print(f"Default: {formatted_current['default']}")
print(f"Short: {formatted_current['short']}")
print(f"Long: {formatted_current['long']}")
print(f"ISO: {formatted_current['iso']}")
print("\nYour Input Date and Time (Formatted):")
print(f"Default: {formatted_user_date['default']}")
print(f"Short: {formatted_user_date['short']}")
print(f"Long: {formatted_user_date['long']}")
print(f"ISO: {formatted_user_date['iso']}")
# Display the time difference
print(f"\nTime Difference: {time_difference}")
# Run the program
if __name__ == "__main__":
main()
Output
Enter a date and time (format: YYYY-MM-DD HH:MM:SS): 2024-12-25 15:30:00
Current Date and Time (Formatted):
Default: 2024-12-27 10:30:15
Short: 12/27/2024
Long: Thursday, December 27, 2024 10:30:15 AM
ISO: 2024-12-27T10:30:15
Your Input Date and Time (Formatted):
Default: 2024-12-25 15:30:00
Short: 12/25/2024
Long: Wednesday, December 25, 2024 03:30:00 PM
ISO: 2024-12-25T15:30:00
Time Difference: 1 day, 19:00:15
Share this Python Exercise