times.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 MySQLdb._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 = " ".join(
  35. [
  36. "{0.year:04}-{0.month:02}-{0.day:02}",
  37. "{0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}",
  38. ]
  39. )
  40. else:
  41. fmt = " ".join(
  42. [
  43. "{0.year:04}-{0.month:02}-{0.day:02}",
  44. "{0.hour:02}:{0.minute:02}:{0.second:02}",
  45. ]
  46. )
  47. return fmt.format(d)
  48. def DateTime_or_None(s):
  49. try:
  50. if len(s) < 11:
  51. return Date_or_None(s)
  52. micros = s[20:]
  53. if len(micros) == 0:
  54. # 12:00:00
  55. micros = 0
  56. elif len(micros) < 7:
  57. # 12:00:00.123456
  58. micros = int(micros) * 10 ** (6 - len(micros))
  59. else:
  60. return None
  61. return datetime(
  62. int(s[:4]), # year
  63. int(s[5:7]), # month
  64. int(s[8:10]), # day
  65. int(s[11:13] or 0), # hour
  66. int(s[14:16] or 0), # minute
  67. int(s[17:19] or 0), # second
  68. micros, # microsecond
  69. )
  70. except ValueError:
  71. return None
  72. def TimeDelta_or_None(s):
  73. try:
  74. h, m, s = s.split(":")
  75. if "." in s:
  76. s, ms = s.split(".")
  77. ms = ms.ljust(6, "0")
  78. else:
  79. ms = 0
  80. if h[0] == "-":
  81. negative = True
  82. else:
  83. negative = False
  84. h, m, s, ms = abs(int(h)), int(m), int(s), int(ms)
  85. td = timedelta(hours=h, minutes=m, seconds=s, microseconds=ms)
  86. if negative:
  87. return -td
  88. else:
  89. return td
  90. except ValueError:
  91. # unpacking or int/float conversion failed
  92. return None
  93. def Time_or_None(s):
  94. try:
  95. h, m, s = s.split(":")
  96. if "." in s:
  97. s, ms = s.split(".")
  98. ms = ms.ljust(6, "0")
  99. else:
  100. ms = 0
  101. h, m, s, ms = int(h), int(m), int(s), int(ms)
  102. return time(hour=h, minute=m, second=s, microsecond=ms)
  103. except ValueError:
  104. return None
  105. def Date_or_None(s):
  106. try:
  107. return date(
  108. int(s[:4]),
  109. int(s[5:7]),
  110. int(s[8:10]),
  111. ) # year # month # day
  112. except ValueError:
  113. return None
  114. def DateTime2literal(d, c):
  115. """Format a DateTime object as an ISO timestamp."""
  116. return string_literal(format_TIMESTAMP(d))
  117. def DateTimeDelta2literal(d, c):
  118. """Format a DateTimeDelta object as a time."""
  119. return string_literal(format_TIMEDELTA(d))