# 63. Python's datetime Module

**Python's `datetime` Module**

The `datetime` module in Python provides classes for manipulating dates and times. It supports operations like formatting, parsing, arithmetic, and comparisons. Below are key features of the `datetime` module along with example code snippets.

***

**1. Getting the Current Date and Time**

The `datetime` module allows you to get the current date and time using the `datetime.now()` function.

```python
import datetime

current_datetime = datetime.datetime.now()
print(current_datetime)  # Output: 2025-01-22 12:00:00.123456 (example)
```

You can also get just the current date or time:

```python
current_date = datetime.date.today()
print(current_date)  # Output: 2025-01-22

current_time = datetime.datetime.now().time()
print(current_time)  # Output: 12:00:00.123456
```

***

**2. Creating Specific Dates and Times**

You can create specific `date`, `time`, or `datetime` objects by passing arguments to their constructors.

```python
from datetime import date, time, datetime

# Create a specific date
specific_date = date(2022, 5, 17)
print(specific_date)  # Output: 2022-05-17

# Create a specific time
specific_time = time(14, 30, 0)
print(specific_time)  # Output: 14:30:00

# Create a specific datetime
specific_datetime = datetime(2022, 5, 17, 14, 30, 0)
print(specific_datetime)  # Output: 2022-05-17 14:30:00
```

***

**3. Formatting Dates and Times**

You can format `datetime` objects into readable strings using the `strftime()` method. The method takes a format string with placeholders.

```python
current_datetime = datetime.datetime.now()

formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)  # Output: 2025-01-22 12:00:00
```

Some commonly used format codes:

* `%Y`: Year with century (e.g., 2025)
* `%m`: Month as a zero-padded decimal number (e.g., 01)
* `%d`: Day of the month (e.g., 22)
* `%H`: Hour (24-hour clock) (e.g., 12)
* `%M`: Minute (e.g., 00)
* `%S`: Second (e.g., 59)

***

**4. Parsing Dates and Times**

You can parse a string representation of a date or time into a `datetime` object using `strptime()`.

```python
date_string = "2025-01-22 14:30:00"
parsed_datetime = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_datetime)  # Output: 2025-01-22 14:30:00
```

***

**5. Date Arithmetic (Adding and Subtracting Dates)**

You can perform arithmetic on `datetime` objects using `timedelta` objects, which represent a difference between two dates or times.

```python
from datetime import timedelta

# Add 10 days to the current date
current_date = datetime.date.today()
new_date = current_date + timedelta(days=10)
print(new_date)  # Output: 2025-02-01 (example)

# Subtract 3 hours from the current time
current_time = datetime.datetime.now().time()
new_time = (datetime.datetime.combine(datetime.date.today(), current_time) - timedelta(hours=3)).time()
print(new_time)  # Output: 09:00:00 (example)
```

***

**6. Comparing Dates and Times**

You can compare `datetime` objects using comparison operators (>, <, ==, etc.).

```python
date1 = datetime.date(2025, 1, 22)
date2 = datetime.date(2025, 2, 1)

print(date1 < date2)  # Output: True
print(date1 == date2)  # Output: False
```

You can also compare `time` and `datetime` objects similarly.

***

**7. Working with Time Zones (Using `pytz`)**

The `datetime` module works with time zones through `timezone` objects. However, to manage time zones more effectively, you can use the `pytz` library.

```python
import pytz
from datetime import datetime

# Get the current time in UTC
utc_time = datetime.now(pytz.utc)
print("UTC Time:", utc_time)

# Convert UTC time to a specific time zone (e.g., US/Eastern)
eastern_time = utc_time.astimezone(pytz.timezone('US/Eastern'))
print("Eastern Time:", eastern_time)
```

***

**8. Getting the Day of the Week**

You can get the day of the week as an integer (0 for Monday, 6 for Sunday) using the `.weekday()` method, or as a string using `.strftime("%A")`.

```python
current_date = datetime.date.today()

# Get the day of the week as an integer (0=Monday, 6=Sunday)
day_of_week = current_date.weekday()
print(day_of_week)  # Output: 1 (for Tuesday)

# Get the day of the week as a string
day_name = current_date.strftime("%A")
print(day_name)  # Output: "Tuesday"
```

***

**9. Working with Time Delays**

You can pause the execution of your program for a certain period using `time.sleep()`, which can be useful for tasks like rate-limiting or scheduling.

```python
import time

print("Starting countdown...")
time.sleep(5)  # Delay for 5 seconds
print("5 seconds have passed.")
```

***

**10. Handling Time Zones with `datetime` Module**

You can work with fixed offset time zones using the `timezone` class within the `datetime` module.

```python
from datetime import datetime, timezone, timedelta

# Define a timezone with a 5-hour offset
tz = timezone(timedelta(hours=5))

# Get current datetime in this timezone
current_time = datetime.now(tz)
print(current_time)  # Output: 2025-01-22 17:00:00+05:00
```

***

**Summary of Common `datetime` Module Features:**

* **`datetime.now()`**: Get the current date and time.
* **`strftime()`**: Format a `datetime` object as a string.
* **`strptime()`**: Parse a string into a `datetime` object.
* **`timedelta`**: Perform arithmetic on dates and times.
* **`weekday()`**: Get the day of the week as an integer.
* **`timezone`**: Work with time zones and offsets.
