Working with Date and Time - Python Programming Exercise

In this exercise, you will develop a Python program that works with date and time. This exercise is perfect for practicing date and time manipulation, user input handling, and error handling in Python. By implementing this program, you will gain hands-on experience in handling date and time operations, user input, and error handling in Python. This exercise not only reinforces your understanding of date and time manipulation but also helps you develop efficient coding practices for managing user interactions.

 Category

Using Extra Libraries

 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

 Copy 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

 More Python Programming Exercises of Using Extra Libraries

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Displaying Directory Contents

    In this exercise, you will develop a Python program that displays the contents of a specified directory. This exercise is perfect for practicing file handling,...

  •  Listing Executable Files in a Directory

    In this exercise, you will develop a Python program that lists all executable files in a specified directory. This exercise is perfect for practicing file hand...

  •  Continuous Date and Time

    In this exercise, you will develop a Python program that continuously displays the current date and time in real-time. This exercise is perfect for practicing ...

  •  Sitemap Generator

    In this exercise, you will develop a Python program that generates a sitemap for a website. This exercise is perfect for practicing web crawling, URL retrieval...

  •  Generating a List of Images as HTML

    In this exercise, you will develop a Python program that generates an HTML file displaying a list of images from a specified directory. This exercise is perfec...

  •  Retrieving System Information

    In this exercise, you will develop a Python program that retrieves and displays system information, such as the operating system, CPU details, memory usage, and disk ...