whenever life put's you in a tough situtation, never say why me! but, try me!

Working with Dates and Times

In this module, we will cover how to work with dates and times in Python using the datetime module. This includes creating date and time objects, formatting them, performing date arithmetic, and understanding how to use time deltas for calculations involving dates and times.


Subtopic 1: Introduction to datetime Module

The datetime module in Python provides classes for manipulating dates and times. The module includes several useful classes like datetime, date, time, and timedelta.

  • datetime class: Combines both date and time information.
  • date class: Represents a date (year, month, day) without time.
  • time class: Represents time (hour, minute, second, microsecond) without date.
  • timedelta class: Represents a difference between two dates or times.
Example: Importing the datetime Module
import datetime

# Get current date and time
current_datetime = datetime.datetime.now()
print(current_datetime)

# Get current date
current_date = datetime.date.today()
print(current_date)

# Get current time
current_time = datetime.datetime.now().time()
print(current_time)

Subtopic 2: Working with Dates and Times

  • Creating datetime objects: You can create datetime objects using the datetime() constructor or by using various methods like today() for the current date, and now() for the current date and time.

  • Accessing components of datetime: You can access components like year, month, day, hour, minute, second, etc., from datetime and date objects.

Example: Creating and Accessing datetime Objects
import datetime

# Create a datetime object
dt = datetime.datetime(2024, 11, 10, 15, 30)
print(dt)  # Output: 2024-11-10 15:30:00

# Access components of a datetime object
print(f"Year: {dt.year}, Month: {dt.month}, Day: {dt.day}")
print(f"Hour: {dt.hour}, Minute: {dt.minute}, Second: {dt.second}")
  • Working with date objects: You can extract the date part using today(), or by specifying the year, month, and day explicitly.
Example: Working with date Objects
import datetime

# Create a date object
date_object = datetime.date(2024, 11, 10)
print(date_object)  # Output: 2024-11-10

# Access components of a date object
print(f"Year: {date_object.year}, Month: {date_object.month}, Day: {date_object.day}")

Subtopic 3: Formatting Dates and Times

The strftime() method is used to convert datetime objects into formatted string representations. You can format the date and time using different formatting codes.

Common Formatting Codes:
  • %Y: Full year (e.g., 2024)
  • %m: Month as a zero-padded decimal (e.g., 11)
  • %d: Day of the month as a zero-padded decimal (e.g., 10)
  • %H: Hour (24-hour clock) as a zero-padded decimal (e.g., 15)
  • %M: Minute as a zero-padded decimal (e.g., 30)
  • %S: Second as a zero-padded decimal (e.g., 45)
Example: Formatting datetime Objects
import datetime

# Get current datetime
now = datetime.datetime.now()

# Format datetime object into a string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date: {formatted_date}")
Example: Formatting a date Object
import datetime

# Create a date object
date_object = datetime.date(2024, 11, 10)

# Format the date object
formatted_date = date_object.strftime("%A, %B %d, %Y")  # Full weekday name, full month name
print(f"Formatted Date: {formatted_date}")

Subtopic 4: Using timedelta for Date Arithmetic

timedelta represents the difference between two dates or times. You can use it to perform operations like adding or subtracting days, hours, minutes, etc.

  • Adding or subtracting time: You can add or subtract timedelta from a datetime or date object.
Example: Using timedelta to Add and Subtract Time
import datetime

# Create a datetime object
dt = datetime.datetime(2024, 11, 10, 15, 30)

# Create a timedelta object (e.g., 5 days)
delta = datetime.timedelta(days=5)

# Add timedelta to datetime object
new_datetime = dt + delta
print(f"New DateTime (After Adding 5 Days): {new_datetime}")

# Subtract timedelta from datetime object
previous_datetime = dt - delta
print(f"Previous DateTime (5 Days Ago): {previous_datetime}")
Example: Using timedelta for Date Arithmetic
import datetime

# Get current date
current_date = datetime.date.today()

# Subtract 10 days from current date
delta = datetime.timedelta(days=10)
new_date = current_date - delta
print(f"New Date (10 Days Ago): {new_date}")

# Add 2 weeks to current date
delta = datetime.timedelta(weeks=2)
future_date = current_date + delta
print(f"Future Date (2 Weeks Later): {future_date}")

Tasks

  1. Task 1: Calculate Your Age

    • Write a program that calculates the user's age based on their birthdate. The program should take the current date and subtract the birthdate, returning the age in years, months, and days.
  2. Task 2: Format a Date

    • Write a program that takes a user’s date of birth in YYYY-MM-DD format and prints it in the format Day, Month Date, Year (e.g., Monday, November 10, 2024).
  3. Task 3: Date Arithmetic

    • Create a program that takes the current date and calculates the date 100 days from today. Display the result.
  4. Task 4: Time Calculation

    • Write a program that calculates the time difference between two given times (e.g., "14:30" and "16:15"). Return the difference in hours and minutes.
  5. Task 5: Days Between Two Dates

    • Write a program that asks the user for two dates (in YYYY-MM-DD format) and calculates the number of days between the two dates.
  6. Task 6: Leap Year Checker

    • Write a program that asks for a year and checks if it is a leap year or not using the datetime module. A leap year occurs every 4 years, except for years divisible by 100 but not by 400.