DateTimeRange Library

2.3.2 · active · verified Thu Apr 16

DateTimeRange (v2.3.2) is a Python library designed to handle operations on time ranges, such as checking time inclusion, finding intersections, truncating, and iterating through ranges. It is actively maintained with frequent updates and supports modern Python versions.

Common errors

Warnings

Install

Imports

Quickstart

Initializes a DateTimeRange object, demonstrates checking for time inclusion, and calculates the intersection with another range. It's crucial to ensure consistent timezone awareness for accurate comparisons.

from datetime import datetime
from datetimerange import DateTimeRange

# Create a DateTimeRange instance
time_range = DateTimeRange("2023-01-01T10:00:00+0900", "2023-01-01T10:10:00+0900")
print(f"Initial range: {time_range}")

# Check if a datetime is within the range
check_time = datetime(2023, 1, 1, 10, 5, 0).astimezone(time_range.start_datetime.tzinfo)
is_within = check_time in time_range
print(f"Is {check_time} within range? {is_within}")

# Create an intersecting range
another_range = DateTimeRange("2023-01-01T10:05:00+0900", "2023-01-01T10:15:00+0900")
intersection = time_range.intersection(another_range)
print(f"Intersection with {another_range}: {intersection}")

view raw JSON →