comparison MySQLdb/times.py @ 11:aef6ea6a9737 MySQLdb

More PyLint-inspired cleanups. Added a bunch of doctests in times.
author adustman
date Mon, 26 Feb 2007 06:03:45 +0000
parents b5a377255eea
children d68fe80ce1c3
comparison
equal deleted inserted replaced
10:3f4c6af70e52 11:aef6ea6a9737
2 2
3 This module provides some Date and Time classes for dealing with MySQL data. 3 This module provides some Date and Time classes for dealing with MySQL data.
4 4
5 Use Python datetime module to handle date and time columns.""" 5 Use Python datetime module to handle date and time columns."""
6 6
7 __revision__ = "$ Revision: $"[11:-2]
8
7 from time import localtime 9 from time import localtime
8 from datetime import date, datetime, time, timedelta 10 from datetime import date, datetime, time, timedelta
9 from _mysql import string_literal 11 from _mysql import string_literal
10 12
13 # These are required for DB-API (PEP-249)
11 Date = date 14 Date = date
12 Time = time 15 Time = time
13 TimeDelta = timedelta 16 TimeDelta = timedelta
14 Timestamp = datetime 17 Timestamp = datetime
15 18
16 DateTimeDeltaType = timedelta
17 DateTimeType = datetime
18
19 def DateFromTicks(ticks): 19 def DateFromTicks(ticks):
20 """Convert UNIX ticks into a date instance.""" 20 """Convert UNIX ticks into a date instance.
21
22 >>> DateFromTicks(1172466380)
23 datetime.date(2007, 2, 25)
24
25 """
21 return date(*localtime(ticks)[:3]) 26 return date(*localtime(ticks)[:3])
22 27
23 def TimeFromTicks(ticks): 28 def TimeFromTicks(ticks):
24 """Convert UNIX ticks into a time instance.""" 29 """Convert UNIX ticks into a time instance.
30
31 >>> TimeFromTicks(1172466380)
32 datetime.time(23, 6, 20)
33
34 """
25 return time(*localtime(ticks)[3:6]) 35 return time(*localtime(ticks)[3:6])
26 36
27 def TimestampFromTicks(ticks): 37 def TimestampFromTicks(ticks):
28 """Convert UNIX ticks into a datetime instance.""" 38 """Convert UNIX ticks into a datetime instance.
39
40 >>> TimestampFromTicks(1172466380)
41 datetime.datetime(2007, 2, 25, 23, 6, 20)
42
43 """
29 return datetime(*localtime(ticks)[:6]) 44 return datetime(*localtime(ticks)[:6])
30 45
31 format_TIME = format_DATE = str 46 format_TIME = format_DATE = str
32 47
33 def format_TIMEDELTA(v): 48 def format_TIMEDELTA(obj):
34 seconds = int(v.seconds) % 60 49 """Format a TIMEDELTA as a string.
35 minutes = int(v.seconds / 60) % 60 50
36 hours = int(v.seconds / 3600) % 24 51 >>> format_TIMEDELTA(timedelta(seconds=-86400))
37 return '%d %d:%d:%d' % (v.days, hours, minutes, seconds) 52 '-1 00:00:00'
53 >>> format_TIMEDELTA(timedelta(hours=73, minutes=15, seconds=32))
54 '3 01:15:32'
55
56 """
57 seconds = int(obj.seconds) % 60
58 minutes = int(obj.seconds / 60) % 60
59 hours = int(obj.seconds / 3600) % 24
60 return '%d %02d:%02d:%02d' % (obj.days, hours, minutes, seconds)
38 61
39 def format_TIMESTAMP(d): 62 def format_TIMESTAMP(obj):
40 return d.strftime("%Y-%m-%d %H:%M:%S") 63 return obj.strftime("%Y-%m-%d %H:%M:%S")
41 64
42 65 def datetime_or_None(obj):
43 def DateTime_or_None(s): 66 if ' ' in obj:
44 if ' ' in s:
45 sep = ' ' 67 sep = ' '
46 elif 'T' in s: 68 elif 'T' in obj:
47 sep = 'T' 69 sep = 'T'
48 else: 70 else:
49 return Date_or_None(s) 71 return date_or_None(obj)
50 72
51 try: 73 try:
52 d, t = s.split(sep, 1) 74 ymd, hms = obj.split(sep, 1)
53 return datetime(*[ int(x) for x in d.split('-')+t.split(':') ]) 75 return datetime(*[ int(x) for x in ymd.split('-')+hms.split(':') ])
54 except: 76 except ValueError:
55 return Date_or_None(s) 77 return date_or_None(obj)
56 78
57 def TimeDelta_or_None(s): 79 def timedelta_or_None(obj):
58 from math import modf 80 from math import modf
59 try: 81 try:
60 h, m, s = s.split(':') 82 hours, minutes, seconds = obj.split(':')
61 td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)), 83 tdelta = timedelta(hours=int(hours), minutes=int(minutes), seconds=int(seconds),
62 microseconds=int(modf(float(s))[0]*1000000)) 84 microseconds=int(modf(float(seconds))[0]*1000000))
63 if h < 0: 85 if hours < 0:
64 return -td 86 return -tdelta
65 else: 87 else:
66 return td 88 return tdelta
67 except: 89 except ValueError:
68 return None 90 return None
69 91
70 def Time_or_None(s): 92 def time_or_None(obj):
71 from math import modf 93 from math import modf
72 try: 94 try:
73 h, m, s = s.split(':') 95 hour, minute, second = obj.split(':')
74 return time(hour=int(h), minute=int(m), second=int(float(s)), 96 return time(hour=int(hour), minute=int(minute), second=int(second),
75 microsecond=int(modf(float(s))[0]*1000000)) 97 microsecond=int(modf(float(second))[0]*1000000))
76 except: 98 except ValueError:
77 return None 99 return None
78 100
79 def Date_or_None(s): 101 def date_or_None(obj):
80 try: return date(*[ int(x) for x in s.split('-',2)]) 102 try:
81 except: return None 103 return date(*[ int(x) for x in obj.split('-',2)])
104 except ValueError:
105 return None
82 106
83 def DateTime2literal(d, c): 107 def datetime_to_sql(obj, conv):
84 """Format a DateTime object as an ISO timestamp.""" 108 """Format a DateTime object as an ISO timestamp."""
85 return string_literal(format_TIMESTAMP(d),c) 109 return string_literal(format_TIMESTAMP(obj), conv)
86 110
87 def DateTimeDelta2literal(d, c): 111 def timedelta_to_sql(obj, conv):
88 """Format a DateTimeDelta object as a time.""" 112 """Format a timedelta as an SQL literal.
89 return string_literal(format_TIMEDELTA(d),c) 113
114 >>> timedelta_to_sql(timedelta(hours=73, minutes=15, seconds=32), {})
115 "'3 01:15:32'"
116
117 """
118 return string_literal(format_TIMEDELTA(obj), conv)
90 119
91 def mysql_timestamp_converter(s): 120 def mysql_timestamp_converter(timestamp):
92 """Convert a MySQL TIMESTAMP to a Timestamp object.""" 121 """Convert a MySQL TIMESTAMP to a Timestamp object.
93 # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME 122
94 if s[4] == '-': return DateTime_or_None(s) 123 MySQL>4.1 returns TIMESTAMP in the same format as DATETIME:
95 s = s + "0"*(14-len(s)) # padding 124
96 parts = map(int, filter(None, (s[:4],s[4:6],s[6:8], 125 >>> mysql_timestamp_converter('2007-02-25 22:32:17')
97 s[8:10],s[10:12],s[12:14]))) 126 datetime.datetime(2007, 2, 25, 22, 32, 17)
98 try: return Timestamp(*parts) 127
99 except: return None 128 MySQL<4.1 uses a big string of numbers:
129
130 >>> mysql_timestamp_converter('20070225223217')
131 datetime.datetime(2007, 2, 25, 22, 32, 17)
132
133 Illegal values are returned as None:
134
135 >>> print mysql_timestamp_converter('2007-02-31 22:32:17')
136 None
137 >>> print mysql_timestamp_converter('00000000000000')
138 None
139
140 """
141 if timestamp[4] == '-':
142 return datetime_or_None(timestamp)
143 timestamp += "0"*(14-len(timestamp)) # padding
144 year, month, day, hour, minute, second = \
145 int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \
146 int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14])
147 try:
148 return datetime(year, month, day, hour, minute, second)
149 except ValueError:
150 return None
151
152 if __name__ == "__main__":
153 import doctest
154 doctest.testmod()
155