util.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. import datetime
  4. def total_seconds(td):
  5. """Get total seconds for timedelta."""
  6. return td.total_seconds()
  7. def is_timestamp(value):
  8. """Check if value is a valid timestamp."""
  9. if isinstance(value, bool):
  10. return False
  11. if not (
  12. isinstance(value, int) or isinstance(value, float) or isinstance(value, str)
  13. ):
  14. return False
  15. try:
  16. float(value)
  17. return True
  18. except ValueError:
  19. return False
  20. # Credit to https://stackoverflow.com/a/1700069
  21. def iso_to_gregorian(iso_year, iso_week, iso_day):
  22. """Converts an ISO week date tuple into a datetime object."""
  23. if not 1 <= iso_week <= 53:
  24. raise ValueError("ISO Calendar week value must be between 1-53.")
  25. if not 1 <= iso_day <= 7:
  26. raise ValueError("ISO Calendar day value must be between 1-7")
  27. # The first week of the year always contains 4 Jan.
  28. fourth_jan = datetime.date(iso_year, 1, 4)
  29. delta = datetime.timedelta(fourth_jan.isoweekday() - 1)
  30. year_start = fourth_jan - delta
  31. gregorian = year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
  32. return gregorian
  33. # Python 2.7 / 3.0+ definitions for isstr function.
  34. try: # pragma: no cover
  35. basestring
  36. def isstr(s):
  37. return isinstance(s, basestring) # noqa: F821
  38. except NameError: # pragma: no cover
  39. def isstr(s):
  40. return isinstance(s, str)
  41. __all__ = ["total_seconds", "is_timestamp", "isstr", "iso_to_gregorian"]