A library that computes the ephemerides.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dateutil.py 2.5 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python3
  2. # Kosmorrolib - The Library To Compute Your Ephemerides
  3. # Copyright (C) 2021 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from datetime import datetime, timezone, timedelta
  18. def translate_to_timezone(date: datetime, to_tz: int):
  19. """Convert a datetime from a timezone to another.
  20. >>> translate_to_timezone(datetime(2021, 6, 9, 5, 0, 0, tzinfo=timezone.utc), 2)
  21. datetime.datetime(2021, 6, 9, 7, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
  22. >>> translate_to_timezone(datetime(2021, 6, 9, 5, 0, 0, tzinfo=timezone(timedelta(hours=1))), 2)
  23. datetime.datetime(2021, 6, 9, 6, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
  24. If the datetime has no timezone information, then it is interpreted as UTC:
  25. >>> translate_to_timezone(datetime(2021, 6, 9, 5, 0, 0), 2)
  26. datetime.datetime(2021, 6, 9, 7, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
  27. """
  28. source_tz = date.tzinfo if date.tzinfo is not None else timezone.utc
  29. return date.replace(tzinfo=source_tz).astimezone(
  30. tz=timezone(timedelta(hours=to_tz))
  31. )
  32. def normalize_datetime(date: datetime) -> datetime:
  33. """Round the seconds in the given datetime
  34. >>> normalize_datetime(datetime(2021, 6, 9, 2, 30, 29))
  35. datetime.datetime(2021, 6, 9, 2, 30)
  36. >>> normalize_datetime(datetime(2021, 6, 9, 2, 30, 30))
  37. datetime.datetime(2021, 6, 9, 2, 31)
  38. >>> normalize_datetime(datetime(2021, 6, 9, 23, 59, 59))
  39. datetime.datetime(2021, 6, 10, 0, 0)
  40. >>> normalize_datetime(datetime(2021, 12, 31, 23, 59, 59))
  41. datetime.datetime(2022, 1, 1, 0, 0)
  42. """
  43. new_date = datetime(date.year, date.month, date.day, date.hour, date.minute)
  44. if date.second >= 30:
  45. new_date += timedelta(minutes=1)
  46. return new_date