datetime-quarter library
datetime-quarter is a simple and lightweight Python library that adds quarter-level support to standard `datetime` objects. It provides a `QuarterDateTime` class, allowing creation of objects representing a specific year and quarter, and methods to easily derive the start and end `datetime` for that quarter. The current version is 1.0.3, and it appears to have a stable but infrequent release cadence.
Common errors
-
ImportError: cannot import name 'QuarterDateTime' from 'datetime_quarter'
cause The `datetime-quarter` library is either not installed or there is a typo in the import statement.fixEnsure the library is installed with `pip install datetime-quarter` and verify the import path is `from datetime_quarter import QuarterDateTime`. -
AttributeError: 'QuarterDateTime' object has no attribute 'day' (or 'hour', 'minute', etc.)
cause `QuarterDateTime` objects represent an entire quarter, not a specific date and time. They do not possess attributes for day, hour, minute, etc., which are specific to `datetime` objects.fixIf you need a `datetime` object with specific date/time components, convert the `QuarterDateTime` to a standard `datetime` using its `.start_of_quarter` or `.end_of_quarter` properties.
Warnings
- gotcha The `QuarterDateTime` object does not inherit directly from `datetime` and thus lacks many standard `datetime` attributes and methods (e.g., `day`, `hour`, `strftime`). It represents a quarter, not a specific point in time.
- gotcha When creating `QuarterDateTime` from a `datetime` object using `QuarterDateTime.from_datetime()`, the quarter is determined solely by the month of the input `datetime`. The day or time components are ignored.
Install
-
pip install datetime-quarter
Imports
- QuarterDateTime
from datetime_quarter import QuarterDateTime
Quickstart
from datetime import datetime
from datetime_quarter import QuarterDateTime
# Create a QuarterDateTime object from a standard datetime
dt_obj = datetime(2023, 7, 15)
q_dt_from_dt = QuarterDateTime.from_datetime(dt_obj)
print(f"From datetime {dt_obj}: Year={q_dt_from_dt.year}, Quarter={q_dt_from_dt.quarter}")
print(f"Start of quarter: {q_dt_from_dt.start_of_quarter}")
print(f"End of quarter: {q_dt_from_dt.end_of_quarter}")
# Create a QuarterDateTime object directly with year and quarter
q_dt_direct = QuarterDateTime(2024, 1)
print(f"Directly created: {q_dt_direct}")
print(f"Start of quarter: {q_dt_direct.start_of_quarter}")
# Perform comparisons
print(f"Is 2023Q1 before 2023Q2? {QuarterDateTime(2023, 1) < QuarterDateTime(2023, 2)}")