PageRenderTime 14ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/historical/timestamp.py

https://bitbucket.org/lindenlab/apiary/
Python | 81 lines | 46 code | 11 blank | 24 comment | 7 complexity | 00717adf60cf7f02d21cdca842a36721 MD5 | raw file
  1. #
  2. # $LicenseInfo:firstyear=2010&license=mit$
  3. #
  4. # Copyright (c) 2010, Linden Research, Inc.
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. # THE SOFTWARE.
  23. # $/LicenseInfo$
  24. #
  25. import math
  26. class TimeStamp(object):
  27. def __init__(self, s=0, us=0):
  28. self.seconds = s
  29. self.micros = int(us)
  30. t = type(s)
  31. if t is float:
  32. (frac_part, int_part) = math.modf(s)
  33. self.seconds = int(int_part)
  34. self.micros = int(round(frac_part * 1.0e6))
  35. elif t is str:
  36. parts = s.split('.')
  37. n = len(parts)
  38. self.seconds = 0
  39. if n >= 1:
  40. self.seconds = int(parts[0])
  41. if n >= 2:
  42. us = int((parts[1] + "0000000")[0:7]) / 10.0
  43. self.micros = int(round(us))
  44. def __str__(self):
  45. return "%d.%06d" % (self.seconds, self.micros)
  46. def __repr__(self):
  47. return "TimeStamp(%d,%d)" % (self.seconds, self.micros)
  48. def __hash__(self):
  49. return hash(self.seconds) ^ hash(self.micros)
  50. def __cmp__(self, other):
  51. r = cmp(self.seconds, other.seconds)
  52. if r == 0:
  53. r = cmp(self.micros, other.micros)
  54. return r
  55. def __add__(self, other):
  56. s = self.seconds + other.seconds
  57. us = self.micros + other.micros
  58. if (us >= 1000000):
  59. us -= 1000000
  60. s += 1
  61. return TimeStamp(s, us)
  62. def __sub__(self, other):
  63. s = self.seconds - other.seconds
  64. us = self.micros - other.micros
  65. if (us < 0):
  66. us += 1000000
  67. s -= 1
  68. return TimeStamp(s, us)
  69. def __float__(self):
  70. return self.seconds + self.micros / 1.0e6