Created
April 13, 2021 07:16
-
-
Save linw1995/f09feeaadcf0274fb02f70011436b4ae to your computer and use it in GitHub Desktop.
Get datetime objects in month range in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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