darwin.py 994 B

12345678910111213141516171819202122232425262728293031323334353637
  1. from __future__ import with_statement
  2. import os
  3. import pytz
  4. import subprocess
  5. _cache_tz = None
  6. def _get_localzone():
  7. pipe = subprocess.Popen(
  8. "systemsetup -gettimezone",
  9. shell=True,
  10. stderr=subprocess.PIPE,
  11. stdout=subprocess.PIPE
  12. )
  13. tzname = pipe.stdout.read().replace(b'Time Zone: ', b'').strip()
  14. if not tzname or tzname not in pytz.all_timezones_set:
  15. # link will be something like /usr/share/zoneinfo/America/Los_Angeles.
  16. link = os.readlink("/etc/localtime")
  17. tzname = link[link.rfind("zoneinfo/") + 9:]
  18. return pytz.timezone(tzname)
  19. def get_localzone():
  20. """Get the computers configured local timezone, if any."""
  21. global _cache_tz
  22. if _cache_tz is None:
  23. _cache_tz = _get_localzone()
  24. return _cache_tz
  25. def reload_localzone():
  26. """Reload the cached localzone. You need to call this if the timezone has changed."""
  27. global _cache_tz
  28. _cache_tz = _get_localzone()
  29. return _cache_tz