You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

145 lines
3.9 KiB

6 years ago
  1. """times module
  2. This module provides some Date and Time classes for dealing with MySQL data.
  3. Use Python datetime module to handle date and time columns.
  4. """
  5. from time import localtime
  6. from datetime import date, datetime, time, timedelta
  7. from _mysql import string_literal
  8. Date = date
  9. Time = time
  10. TimeDelta = timedelta
  11. Timestamp = datetime
  12. DateTimeDeltaType = timedelta
  13. DateTimeType = datetime
  14. def DateFromTicks(ticks):
  15. """Convert UNIX ticks into a date instance."""
  16. return date(*localtime(ticks)[:3])
  17. def TimeFromTicks(ticks):
  18. """Convert UNIX ticks into a time instance."""
  19. return time(*localtime(ticks)[3:6])
  20. def TimestampFromTicks(ticks):
  21. """Convert UNIX ticks into a datetime instance."""
  22. return datetime(*localtime(ticks)[:6])
  23. format_TIME = format_DATE = str
  24. def format_TIMEDELTA(v):
  25. seconds = int(v.seconds) % 60
  26. minutes = int(v.seconds // 60) % 60
  27. hours = int(v.seconds // 3600) % 24
  28. return '%d %d:%d:%d' % (v.days, hours, minutes, seconds)
  29. def format_TIMESTAMP(d):
  30. """
  31. :type d: datetime.datetime
  32. """
  33. if d.microsecond:
  34. fmt = "{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}"
  35. else:
  36. fmt = "{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}"
  37. return fmt.format(d)
  38. def DateTime_or_None(s):
  39. try:
  40. if len(s) < 11:
  41. return Date_or_None(s)
  42. micros = s[20:]
  43. if len(micros) == 0:
  44. # 12:00:00
  45. micros = 0
  46. elif len(micros) < 7:
  47. # 12:00:00.123456
  48. micros = int(micros) * 10 ** (6 - len(micros))
  49. else:
  50. return None
  51. return datetime(
  52. int(s[:4]), # year
  53. int(s[5:7]), # month
  54. int(s[8:10]), # day
  55. int(s[11:13] or 0), # hour
  56. int(s[14:16] or 0), # minute
  57. int(s[17:19] or 0), # second
  58. micros, # microsecond
  59. )
  60. except ValueError:
  61. return None
  62. def TimeDelta_or_None(s):
  63. try:
  64. h, m, s = s.split(':')
  65. if '.' in s:
  66. s, ms = s.split('.')
  67. ms = ms.ljust(6, '0')
  68. else:
  69. ms = 0
  70. if h[0] == '-':
  71. negative = True
  72. else:
  73. negative = False
  74. h, m, s, ms = abs(int(h)), int(m), int(s), int(ms)
  75. td = timedelta(hours=h, minutes=m, seconds=s,
  76. microseconds=ms)
  77. if negative:
  78. return -td
  79. else:
  80. return td
  81. except ValueError:
  82. # unpacking or int/float conversion failed
  83. return None
  84. def Time_or_None(s):
  85. try:
  86. h, m, s = s.split(':')
  87. if '.' in s:
  88. s, ms = s.split('.')
  89. ms = ms.ljust(6, '0')
  90. else:
  91. ms = 0
  92. h, m, s, ms = int(h), int(m), int(s), int(ms)
  93. return time(hour=h, minute=m, second=s,
  94. microsecond=ms)
  95. except ValueError:
  96. return None
  97. def Date_or_None(s):
  98. try:
  99. return date(
  100. int(s[:4]), # year
  101. int(s[5:7]), # month
  102. int(s[8:10]), # day
  103. )
  104. except ValueError:
  105. return None
  106. def DateTime2literal(d, c):
  107. """Format a DateTime object as an ISO timestamp."""
  108. return string_literal(format_TIMESTAMP(d), c)
  109. def DateTimeDelta2literal(d, c):
  110. """Format a DateTimeDelta object as a time."""
  111. return string_literal(format_TIMEDELTA(d),c)
  112. def mysql_timestamp_converter(s):
  113. """Convert a MySQL TIMESTAMP to a Timestamp object."""
  114. # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
  115. if s[4] == '-': return DateTime_or_None(s)
  116. s = s + "0"*(14-len(s)) # padding
  117. parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
  118. s[8:10],s[10:12],s[12:14])))
  119. try:
  120. return Timestamp(*parts)
  121. except (SystemExit, KeyboardInterrupt):
  122. raise # pragma: no cover
  123. except:
  124. return None

Powered by TurnKey Linux.