A library that computes the ephemerides.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dateutil.py 2.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(
  44. date.year, date.month, date.day, date.hour, date.minute
  45. ).replace(microsecond=0)
  46. if date.second >= 30:
  47. new_date += timedelta(minutes=1)
  48. return new_date