pytz.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # coding=utf-8
  2. #
  3. # This file is part of Hypothesis, which may be found at
  4. # https://github.com/HypothesisWorks/hypothesis-python
  5. #
  6. # Most of this work is copyright (C) 2013-2018 David R. MacIver
  7. # (david@drmaciver.com), but it contains contributions by others. See
  8. # CONTRIBUTING.rst for a full list of people who may hold copyright, and
  9. # consult the git log if you need to determine who owns an individual
  10. # contribution.
  11. #
  12. # This Source Code Form is subject to the terms of the Mozilla Public License,
  13. # v. 2.0. If a copy of the MPL was not distributed with this file, You can
  14. # obtain one at http://mozilla.org/MPL/2.0/.
  15. #
  16. # END HEADER
  17. """This module provides ``pytz`` timezones.
  18. You can use this strategy to make
  19. :py:func:`hypothesis.strategies.datetimes` and
  20. :py:func:`hypothesis.strategies.times` produce timezone-aware values.
  21. """
  22. from __future__ import division, print_function, absolute_import
  23. import datetime as dt
  24. import pytz
  25. import hypothesis.strategies as st
  26. __all__ = ['timezones']
  27. @st.cacheable
  28. @st.defines_strategy
  29. def timezones():
  30. """Any timezone in the Olsen database, as a pytz tzinfo object.
  31. This strategy minimises to UTC, or the smallest possible fixed
  32. offset, and is designed for use with
  33. :py:func:`hypothesis.strategies.datetimes`.
  34. """
  35. all_timezones = [pytz.timezone(tz) for tz in pytz.all_timezones]
  36. # Some timezones have always had a constant offset from UTC. This makes
  37. # them simpler than timezones with daylight savings, and the smaller the
  38. # absolute offset the simpler they are. Of course, UTC is even simpler!
  39. static = [pytz.UTC] + sorted(
  40. (t for t in all_timezones if isinstance(t, pytz.tzfile.StaticTzInfo)),
  41. key=lambda tz: abs(tz.utcoffset(dt.datetime(2000, 1, 1)))
  42. )
  43. # Timezones which have changed UTC offset; best ordered by name.
  44. dynamic = [tz for tz in all_timezones if tz not in static]
  45. return st.sampled_from(static + dynamic)