times.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. import math
  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. return d.strftime("%Y-%m-%d %H:%M:%S")
  31. def DateTime_or_None(s):
  32. if ' ' in s:
  33. sep = ' '
  34. elif 'T' in s:
  35. sep = 'T'
  36. else:
  37. return Date_or_None(s)
  38. try:
  39. d, t = s.split(sep, 1)
  40. return datetime(*[ int(x) for x in d.split('-')+t.split(':') ])
  41. except:
  42. return Date_or_None(s)
  43. def TimeDelta_or_None(s):
  44. try:
  45. h, m, s = s.split(':')
  46. h, m, s = int(h), int(m), float(s)
  47. td = timedelta(hours=abs(h), minutes=m, seconds=int(s),
  48. microseconds=int(math.modf(s)[0] * 1000000))
  49. if h < 0:
  50. return -td
  51. else:
  52. return td
  53. except ValueError:
  54. # unpacking or int/float conversion failed
  55. return None
  56. def Time_or_None(s):
  57. try:
  58. h, m, s = s.split(':')
  59. h, m, s = int(h), int(m), float(s)
  60. return time(hour=h, minute=m, second=int(s),
  61. microsecond=int(math.modf(s)[0] * 1000000))
  62. except ValueError:
  63. return None
  64. def Date_or_None(s):
  65. try: return date(*[ int(x) for x in s.split('-',2)])
  66. except: return None
  67. def DateTime2literal(d, c):
  68. """Format a DateTime object as an ISO timestamp."""
  69. return string_literal(format_TIMESTAMP(d),c)
  70. def DateTimeDelta2literal(d, c):
  71. """Format a DateTimeDelta object as a time."""
  72. return string_literal(format_TIMEDELTA(d),c)
  73. def mysql_timestamp_converter(s):
  74. """Convert a MySQL TIMESTAMP to a Timestamp object."""
  75. # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
  76. if s[4] == '-': return DateTime_or_None(s)
  77. s = s + "0"*(14-len(s)) # padding
  78. parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
  79. s[8:10],s[10:12],s[12:14])))
  80. try: return Timestamp(*parts)
  81. except: return None