git_dates.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright 2016 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Utility module for dealing with Git timestamps."""
  5. import datetime
  6. def timestamp_offset_to_datetime(timestamp, offset):
  7. """Converts a timestamp + offset into a datetime.datetime.
  8. Useful for dealing with the output of porcelain commands, which provide
  9. times as timestamp and offset strings.
  10. Args:
  11. timestamp: An int UTC timestamp, or a string containing decimal digits.
  12. offset: A str timezone offset. e.g., '-0800'.
  13. Returns:
  14. A tz-aware datetime.datetime for this timestamp.
  15. """
  16. timestamp = int(timestamp)
  17. tz = FixedOffsetTZ.from_offset_string(offset)
  18. return datetime.datetime.fromtimestamp(timestamp, tz)
  19. def datetime_string(dt):
  20. """Converts a tz-aware datetime.datetime into a string in git format."""
  21. return dt.strftime('%Y-%m-%d %H:%M:%S %z')
  22. # Adapted from: https://docs.python.org/2/library/datetime.html#tzinfo-objects
  23. class FixedOffsetTZ(datetime.tzinfo):
  24. def __init__(self, offset, name):
  25. datetime.tzinfo.__init__(self)
  26. self.__offset = offset
  27. self.__name = name
  28. def __repr__(self): # pragma: no cover
  29. return '{}({!r}, {!r})'.format(
  30. type(self).__name__, self.__offset, self.__name)
  31. @classmethod
  32. def from_offset_string(cls, offset):
  33. try:
  34. hours = int(offset[:-2])
  35. minutes = int(offset[-2:])
  36. except ValueError:
  37. return cls(datetime.timedelta(0), 'UTC')
  38. delta = datetime.timedelta(hours=hours, minutes=minutes)
  39. return cls(delta, offset)
  40. def utcoffset(self, dt):
  41. return self.__offset
  42. def tzname(self, dt):
  43. return self.__name
  44. def dst(self, dt):
  45. return datetime.timedelta(0)