weekday.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """Get the ISO standard day number of the week from a given day string."""
  18. from __future__ import annotations
  19. import enum
  20. from typing import Iterable
  21. @enum.unique
  22. class WeekDay(enum.IntEnum):
  23. """Python Enum containing Days of the Week."""
  24. MONDAY = 1
  25. TUESDAY = 2
  26. WEDNESDAY = 3
  27. THURSDAY = 4
  28. FRIDAY = 5
  29. SATURDAY = 6
  30. SUNDAY = 7
  31. @classmethod
  32. def get_weekday_number(cls, week_day_str: str):
  33. """
  34. Return the ISO Week Day Number for a Week Day.
  35. :param week_day_str: Full Name of the Week Day. Example: "Sunday"
  36. :return: ISO Week Day Number corresponding to the provided Weekday
  37. """
  38. sanitized_week_day_str = week_day_str.upper()
  39. if sanitized_week_day_str not in cls.__members__:
  40. raise AttributeError(f'Invalid Week Day passed: "{week_day_str}"')
  41. return cls[sanitized_week_day_str]
  42. @classmethod
  43. def convert(cls, day: str | WeekDay) -> int:
  44. """Return the day number in the week."""
  45. if isinstance(day, WeekDay):
  46. return day
  47. return cls.get_weekday_number(week_day_str=day)
  48. @classmethod
  49. def validate_week_day(
  50. cls,
  51. week_day: str | WeekDay | Iterable[str] | Iterable[WeekDay],
  52. ) -> set[int]:
  53. """Validate each item of iterable and create a set to ease compare of values."""
  54. if not isinstance(week_day, Iterable):
  55. if isinstance(week_day, WeekDay):
  56. week_day = {week_day}
  57. else:
  58. raise TypeError(
  59. f"Unsupported Type for week_day parameter: {type(week_day)}."
  60. "Input should be iterable type:"
  61. "str, set, list, dict or Weekday enum type"
  62. )
  63. if isinstance(week_day, str):
  64. week_day = {week_day}
  65. return {cls.convert(item) for item in week_day}