bolster.utils.dt
Datetime rounding and timezone utilities.
Provides helpers that coerce datetime.datetime and
datetime.date objects to useful calendar boundaries (week, month)
and to UTC midnight, without depending on any third-party libraries.
Example
>>> from bolster.utils.dt import round_to_week, round_to_month
>>> from datetime import date
>>> round_to_week(date(2024, 3, 13)) # Wednesday → previous Monday
datetime.date(2024, 3, 11)
>>> round_to_month(date(2024, 3, 13))
datetime.date(2024, 3, 1)
Functions
|
Return a date for the Monday of the week containing the given date. |
|
Return a date for the first day of the month containing the given date. |
|
Return UTC midnight for the calendar date of a given datetime. |
Module Contents
- bolster.utils.dt.round_to_week(dt)[source]
Return a date for the Monday of the week containing the given date.
- Parameters:
dt (datetime.datetime | datetime.date) – A
datetime.datetimeordatetime.dateto round.- Returns:
The Monday on or before
dtas adatetime.date.- Return type:
Example
>>> round_to_week(datetime(2018,8,9,12,1)) datetime.date(2018, 8, 6) >>> round_to_week(date(2018,8,9)) datetime.date(2018, 8, 6)
- bolster.utils.dt.round_to_month(dt)[source]
Return a date for the first day of the month containing the given date.
- Parameters:
dt (datetime.datetime | datetime.date) – A
datetime.datetimeordatetime.dateto round.- Returns:
The first day of the month of
dtas adatetime.date.- Return type:
Example
>>> round_to_month(datetime(2018,8,9,12,1)) datetime.date(2018, 8, 1) >>> round_to_month(date(2018,8,9)) datetime.date(2018, 8, 1)
- bolster.utils.dt.utc_midnight_on(dt)[source]
Return UTC midnight for the calendar date of a given datetime.
Converts any
datetime.datetimeto00:00:00 UTCon the same calendar date, regardless of the original time or timezone offset. This is useful when a downstream service requires UTC-naive timestamps or rejects sub-day granularity.- Parameters:
dt (datetime.datetime) – A
datetime.datetimewhose calendar date is used. The time component and any timezone info are ignored.- Returns:
A timezone-aware
datetime.datetimeat00:00:00 UTCon the same calendar date asdt.- Return type:
Example
>>> utc_midnight_on(datetime(2018,9,1,12,12)) datetime.datetime(2018, 9, 1, 0, 0, tzinfo=datetime.timezone.utc)
>>> utc_midnight_on(datetime(2018,9,1,12,12, tzinfo=timezone(timedelta(hours=-13)))) datetime.datetime(2018, 9, 1, 0, 0, tzinfo=datetime.timezone.utc)