Skip to content

Instantly share code, notes, and snippets.

@linw1995
Created April 13, 2021 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linw1995/f09feeaadcf0274fb02f70011436b4ae to your computer and use it in GitHub Desktop.
Save linw1995/f09feeaadcf0274fb02f70011436b4ae to your computer and use it in GitHub Desktop.
Get datetime objects in month range in Python.
import calendar
import dataclasses
from datetime import datetime, timezone
@dataclasses.dataclass
class DatetimeRange:
begin: datetime
end: datetime
@classmethod
def month_range(cls, year, month, tzinfo=None):
_, month_date_size = calendar.monthrange(year, month)
return cls(
begin=datetime.min.replace(year=year, month=month, day=1).astimezone(
tzinfo
),
end=datetime.max.replace(
year=year, month=month, day=month_date_size
).astimezone(tzinfo),
)
if __name__ == "__main__":
dt_range = DatetimeRange.month_range(2021, 3)
print(dt_range.begin, dt_range.end)
# 2021-03-01 00:00:00+08:00 2021-03-31 23:59:59.999999+08:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment