Datetime Utilities

smith_utils.datetime.ensure_date(date_input: str | date | None) date[source]

Converts various date input formats into a datetime.date object.

This function accepts a string, a datetime.date object, or a None value to produce a datetime.date object. If the input is None, the current date is returned. String inputs are first stripped of leading and trailing whitespace, and the function attempts to parse the string as an ISO 8601 formatted date. If the ISO 8601 parsing fails, the input is passed to a fallback parsing function for stricter date parsing.

Raises:
  • ValueError – If the input string cannot be parsed into a valid date

  • via both ISO 8601 and the fallback parsing mechanism.

Parameters:
  • date_input (str | datetime.date | None) – The input to be converted

  • a (to a datetime.date object. This can be a string representing)

  • date

  • itself (a datetime.date object)

  • None. (or)

Returns:

A valid datetime.date object corresponding to the provided input, or the current date if the input is None.

Return type:

datetime.date

smith_utils.datetime.format_ordinal(n: int) str[source]

Converts an integer to its ordinal representation as a string.

The function takes an integer input and returns the ordinal form of the number as a string with its appropriate suffix. For example, 1 becomes “1st”, 2 becomes “2nd”, and so on. The suffix rules account for the exceptional cases such as numbers ending in 11, 12, or 13.

Parameters:

n (int) – The integer to be converted to its ordinal equivalent.

Returns:

The ordinal representation of the input number.

Return type:

str

smith_utils.datetime.parse_strict_date(date_str: str) date[source]

Parses a given date string into a datetime.date object.

This function attempts to parse the input date string in various formats while adhering to strict expectations for valid date representations. It supports both basic (YYYYMMDD) and extended (YYYY-MM-DD) formats and rejects ambiguous or malformed inputs. The function raises an error if the provided string does not conform to the acceptable formats.

Note

The returned datetime.date object is naive and does not retain any time zone information. If the input string contains a time component or time zone identifier (e.g., after a ‘T’ or space), it is simply discarded without any time zone conversion. This means a UTC timestamp might represent a different calendar date in a local time zone.

Parameters:

date_str (str) – The date string to be parsed. It is expected to be in either basic (YYYYMMDD) or extended (YYYY-MM-DD) format.

Returns:

A date object representing the parsed date.

Return type:

datetime.date

Raises:

ValueError – If the input string contains an ambiguous or invalid date.