You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.9 KiB

  1. # Copyright 2020 Camptocamp SA
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
  3. from datetime import date, datetime
  4. import pytz
  5. UTC_TZ = pytz.timezone("UTC")
  6. def tz_to_tz_naive_datetime(from_tz, to_tz, date_time):
  7. """
  8. Convert tz-naive datetime from a specifc tz to a tz-naive datetime of a specific tz
  9. :param from_tz: pytz.timezone object or tz selection value
  10. :param to_tz: pytz.timezone object or tz selection value
  11. :param date_time: tz-naive datetime.datetime object
  12. :return: tz-naive datetime.datetime object
  13. """
  14. if isinstance(from_tz, str):
  15. from_tz = pytz.timezone(from_tz)
  16. if isinstance(to_tz, str):
  17. to_tz = pytz.timezone(to_tz)
  18. return from_tz.localize(date_time).astimezone(to_tz).replace(tzinfo=None)
  19. def tz_to_utc_naive_datetime(from_tz, date_time):
  20. return tz_to_tz_naive_datetime(from_tz, UTC_TZ, date_time)
  21. def utc_to_tz_naive_datetime(to_tz, date_time):
  22. return tz_to_tz_naive_datetime(UTC_TZ, to_tz, date_time)
  23. def tz_to_tz_time(from_tz, to_tz, time, base_date=None):
  24. """
  25. Convert datetime.time from a specific tz to a datetime.time of a specific tz
  26. :param from_tz: pytz.timezone object or tz selection value
  27. :param to_tz: pytz.timezone object or tz selection value
  28. :param time: datetime.time object
  29. :param base_date: OPTIONAL datetime.date or datetime.datetime object to use
  30. for the conversion
  31. :return: datetime.time object
  32. """
  33. # Combine time with a date
  34. if base_date is None:
  35. base_date = date.today()
  36. date_time = datetime.combine(base_date, time)
  37. new_date_time = tz_to_tz_naive_datetime(from_tz, to_tz, date_time)
  38. return new_date_time.time()
  39. def tz_to_utc_time(from_tz, time, base_date=None):
  40. return tz_to_tz_time(from_tz, UTC_TZ, time, base_date=base_date)
  41. def utc_to_tz_time(to_tz, time, base_date=None):
  42. return tz_to_tz_time(UTC_TZ, to_tz, time, base_date=base_date)