Date Utilities

Module: ppc_robot_lib.utils.date

class MonthOfDateRange(index, start, end)[source]
add_months(dt, months, keep_last_day=False)[source]

Add the given number of months to the given date or datetime. If the resulting month has less days than the input month, last day of the month will be used.

If you set keep_last_day=True, the resulting month has more days, and the input date was the last day of the month, the last day of the resulting month will be used.

Examples:

>>> from datetime import date
>>> add_months(date(2020, 1, 31), months=1)
date(2020, 2, 28)
>>> add_months(date(2020, 1, 31), months=2)
date(2020, 3, 31)
>>> add_months(date(2020, 2, 28), months=1, keep_last_day=False)
date(2020, 3, 28)
>>> add_months(date(2020, 2, 28), months=1, keep_last_day=True)
date(2020, 3, 31)
Parameters:
  • dt (date | datetime) – Input date or datetime.

  • months (int) – Number of months to add.

  • keep_last_day – If the input date was the last day of the month, use the last day of month in the output.

Return type:

date | datetime

Returns:

Resulting date or datetime.

get_month_in_date_range(dt, date_range_start, date_range_end, keep_last_day=True)[source]

Helper function for determining current month in a date range.

Parameters:
  • dt (datetime) – Point in time inside the date range.

  • date_range_start (datetime) – Start of the date range.

  • date_range_end (datetime) – End of the date range.

  • keep_last_day – Keep the last day of month when determining end of months.

Return type:

MonthOfDateRange

Returns:

Info about the current month.

get_previous_period(start_date, end_date)[source]

Takes date range and creates a new date range with the exact number of days which precedes it. E.g. For 2019-01-10 - 2019-01-18, this function will return 2019-01-01 - 2019-01-09

Parameters:
  • start_date (date) – Start date.

  • end_date (date) – End date.

Return type:

tuple[date, date]

Returns:

Date range that precedes the given one.

midnight(dt)[source]

Get datetime of dt at midnight.

today_in_timezone(tz)[source]

Get datetime representing start of current day in the given timezone.

Parameters:

tz (timezone | None) – Timezone. If not given, UTC will be used.

Return type:

datetime

Returns:

Start of the current day.

tzinfo(time_zone)[source]

Cached pytz.timezone.

Parameters:

time_zone (str) – timezone identifier

Return type:

tzinfo

Returns:

datetime.tzinfo

:raises pytz.UnknownTimeZoneError in case of time_zone is unknown timezone identifier.