ee_date.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. """A wrapper for dates."""
  3. # pylint: disable=g-bad-import-order
  4. import datetime
  5. import math
  6. from . import apifunction
  7. from . import computedobject
  8. from . import ee_exception
  9. from . import ee_types as types
  10. from . import serializer
  11. # Using lowercase function naming to match the JavaScript names.
  12. # pylint: disable=g-bad-name
  13. class Date(computedobject.ComputedObject):
  14. """An object to represent dates."""
  15. _initialized = False
  16. # Tell pytype to not complain about dynamic attributes.
  17. _HAS_DYNAMIC_ATTRIBUTES = True
  18. def __init__(self, date, opt_tz=None):
  19. """Construct a date.
  20. This sends all inputs (except another Date) through the Date function.
  21. This constructor accepts the following args:
  22. 1) A bare date.
  23. 2) An ISO string
  24. 3) An integer number of milliseconds since the epoch.
  25. 4) A ComputedObject.
  26. Args:
  27. date: The date to wrap.
  28. opt_tz: An optional timezone, only usable with a string date.
  29. """
  30. self.initialize()
  31. func = apifunction.ApiFunction('Date')
  32. args = None
  33. varName = None
  34. if isinstance(date, datetime.datetime):
  35. args = {'value':
  36. math.floor(serializer.DatetimeToMicroseconds(date) / 1000)}
  37. elif types.isNumber(date):
  38. args = {'value': date}
  39. elif isinstance(date, str):
  40. args = {'value': date}
  41. if opt_tz:
  42. if isinstance(opt_tz, str):
  43. args['timeZone'] = opt_tz
  44. else:
  45. raise ee_exception.EEException(
  46. 'Invalid argument specified for ee.Date(..., opt_tz): %s' % date)
  47. elif isinstance(date, computedobject.ComputedObject):
  48. if date.func and date.func.getSignature()['returns'] == 'Date':
  49. # If it's a call that's already returning a Date, just cast.
  50. func = date.func
  51. args = date.args
  52. varName = date.varName
  53. else:
  54. args = {'value': date}
  55. else:
  56. raise ee_exception.EEException(
  57. 'Invalid argument specified for ee.Date(): %s' % date)
  58. super(Date, self).__init__(func, args, varName)
  59. @classmethod
  60. def initialize(cls):
  61. """Imports API functions to this class."""
  62. if not cls._initialized:
  63. apifunction.ApiFunction.importApi(cls, 'Date', 'Date')
  64. cls._initialized = True
  65. @classmethod
  66. def reset(cls):
  67. """Removes imported API functions from this class."""
  68. apifunction.ApiFunction.clearApi(cls)
  69. cls._initialized = False
  70. @staticmethod
  71. def name():
  72. return 'Date'