Python Date and Time

The manipulation of dates is one of the most common things in Python, whether it’s data analysis, automating tasks, or just work with time-sensitive information. Python has a lot of tools and libraries that support date and time, with the most commonly used module being the datetime module.

1. The datetime Module

The datetime module provides classes for manipulating dates and times. Here are the main classes in this module:

  • date: Handles dates (year, month, day).
  • time: Time. Handles times (hours, minutes, seconds, microseconds).
  • datetime: Combines date and time information.
  • timedelta: A duration, or the difference between two dates or times.

2. Working with Dates

Creating a Date Object

The date class allows you to create and manipulate dates.

from datetime import date

# Create a date object
d = date(2024, 12, 21) # Year, Month, Day
print(d) # Output: 2024-12-21

Getting Today’s Date

You can use date.today() to get the current date.

from datetime import date

today = date.today()
print(today) # Output: Current date (e.g., 2024-12-21)

Accessing Date Components

You can access the year, month, and day using attributes.

print(today.year) # Output: 2024
print(today.month) # Output: 12
print(today.day) # Output: 21

3. Formatting Dates

The strftime() method formats a date object into a string.

formatted_date = today.strftime("%B %d, %Y") # Full month name, day, year
print(formatted_date) # Output: December 21, 2024

Common Format Codes:

  • %Y: Year. Example: 2024
  • %m: Month in zero-padding. Example: 12
  • %B: Full month name. Example: December
  • %d: Day of the month. Example: 21

4. Parsing Dates

The strptime() method parses a string into a date or datetime object.

from datetime import datetime

date_string = "2024-12-21"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d").date()
print(parsed_date) # Output: 2024-12-21

5. Date Arithmetic

Using the timedelta class, you can perform operations like adding or subtracting days.

from datetime import timedelta

# Add 10 days
future_date = today + timedelta(days=10)
print(future_date) # Output: 2024-12-31

# Subtract 10 days
past_date = today - timedelta(days=10)
print(past_date) # Output: 2024-12-11

6. Combining Date and Time

The datetime class combines both date and time.

from datetime import datetime

# Create a datetime object
dt = datetime(2024, 12, 21, 14, 30, 0) # Year, Month, Day, Hour, Minute, Second
print(dt) # Output: 2024-12-21 14:30:00

You can also get the current date and time using datetime.now().

current_datetime = datetime.now()
print(current_datetime) # Output: Current date and time

7. Practical Examples

Calculate the Difference Between Two Dates

date1 = date(2024, 12, 21)
date2 = date(2025, 1, 1)

difference = date2 - date1
print(difference.days) # Output: 11

Check for a Leap Year

def is_leap_year(year):
   return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

print(is_leap_year(2024)) # Output: True
print(is_leap_year(2023)) # Output: False

8. Additional Libraries

  • time module: Supplies the lower-level time functionality.
  • calendar module: Provides specific calendar functions, such as determining weekdays or leap years.
  • pytz library (third-party): For handling time zones.
  • dateutil library (third-party): For advanced date manipulation and parsing.

Key Takeaways

  • The datetime module is a versatile module that supports many common date operations.
  • Use strftime() and strptime() for formatting and parsing dates.
  • For time zones and further functionality, third-party libraries like pytz or dateutil come into play.