comparison MySQLdb/times.py @ 12:d68fe80ce1c3 MySQLdb

More docstrings and doctests for times and other cleanups.
author adustman
date Mon, 26 Feb 2007 17:04:04 +0000
parents aef6ea6a9737
children eb90cceaee92
comparison
equal deleted inserted replaced
11:aef6ea6a9737 12:d68fe80ce1c3
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 21
22 >>> DateFromTicks(1172466380) 22 >>> DateFromTicks(1172466380)
23 datetime.date(2007, 2, 25) 23 datetime.date(2007, 2, 25)
24 24 >>> DateFromTicks(0)
25 datetime.date(1969, 12, 31)
26 >>> DateFromTicks(2**31-1)
27 datetime.date(2038, 1, 18)
28
29 This is a standard DB-API constructor.
25 """ 30 """
26 return date(*localtime(ticks)[:3]) 31 return date(*localtime(ticks)[:3])
27 32
28 def TimeFromTicks(ticks): 33 def TimeFromTicks(ticks):
29 """Convert UNIX ticks into a time instance. 34 """Convert UNIX ticks into a time instance.
30 35
31 >>> TimeFromTicks(1172466380) 36 >>> TimeFromTicks(1172466380)
32 datetime.time(23, 6, 20) 37 datetime.time(23, 6, 20)
33 38 >>> TimeFromTicks(0)
39 datetime.time(18, 0)
40 >>> TimeFromTicks(2**31-1)
41 datetime.time(21, 14, 7)
42
43 This is a standard DB-API constructor.
34 """ 44 """
35 return time(*localtime(ticks)[3:6]) 45 return time(*localtime(ticks)[3:6])
36 46
37 def TimestampFromTicks(ticks): 47 def TimestampFromTicks(ticks):
38 """Convert UNIX ticks into a datetime instance. 48 """Convert UNIX ticks into a datetime instance.
39 49
40 >>> TimestampFromTicks(1172466380) 50 >>> TimestampFromTicks(1172466380)
41 datetime.datetime(2007, 2, 25, 23, 6, 20) 51 datetime.datetime(2007, 2, 25, 23, 6, 20)
42 52 >>> TimestampFromTicks(0)
53 datetime.datetime(1969, 12, 31, 18, 0)
54 >>> TimestampFromTicks(2**31-1)
55 datetime.datetime(2038, 1, 18, 21, 14, 7)
56
57 This is a standard DB-API constructor.
43 """ 58 """
44 return datetime(*localtime(ticks)[:6]) 59 return datetime(*localtime(ticks)[:6])
45 60
46 format_TIME = format_DATE = str 61 def timedelta_to_str(obj):
47 62 """Format a timedelta as a string.
48 def format_TIMEDELTA(obj): 63
49 """Format a TIMEDELTA as a string. 64 >>> timedelta_to_str(timedelta(seconds=-86400))
50
51 >>> format_TIMEDELTA(timedelta(seconds=-86400))
52 '-1 00:00:00' 65 '-1 00:00:00'
53 >>> format_TIMEDELTA(timedelta(hours=73, minutes=15, seconds=32)) 66 >>> timedelta_to_str(timedelta(hours=73, minutes=15, seconds=32))
54 '3 01:15:32' 67 '3 01:15:32'
55 68
56 """ 69 """
57 seconds = int(obj.seconds) % 60 70 seconds = int(obj.seconds) % 60
58 minutes = int(obj.seconds / 60) % 60 71 minutes = int(obj.seconds / 60) % 60
59 hours = int(obj.seconds / 3600) % 24 72 hours = int(obj.seconds / 3600) % 24
60 return '%d %02d:%02d:%02d' % (obj.days, hours, minutes, seconds) 73 return '%d %02d:%02d:%02d' % (obj.days, hours, minutes, seconds)
61 74
62 def format_TIMESTAMP(obj): 75 def datetime_to_str(obj):
76 """Convert a datetime to an ISO-format string.
77
78 >>> datetime_to_str(datetime(2007, 2, 25, 23, 6, 20))
79 '2007-02-25 23:06:20'
80
81 """
63 return obj.strftime("%Y-%m-%d %H:%M:%S") 82 return obj.strftime("%Y-%m-%d %H:%M:%S")
64 83
65 def datetime_or_None(obj): 84 def datetime_or_None(obj):
85 """Returns a DATETIME or TIMESTAMP column value as a datetime object:
86
87 >>> datetime_or_None('2007-02-25 23:06:20')
88 datetime.datetime(2007, 2, 25, 23, 6, 20)
89 >>> datetime_or_None('2007-02-25T23:06:20')
90 datetime.datetime(2007, 2, 25, 23, 6, 20)
91
92 Illegal values are returned as None:
93
94 >>> datetime_or_None('2007-02-31T23:06:20') is None
95 True
96 >>> datetime_or_None('0000-00-00 00:00:00') is None
97 True
98
99 """
66 if ' ' in obj: 100 if ' ' in obj:
67 sep = ' ' 101 sep = ' '
68 elif 'T' in obj: 102 elif 'T' in obj:
69 sep = 'T' 103 sep = 'T'
70 else: 104 else:
75 return datetime(*[ int(x) for x in ymd.split('-')+hms.split(':') ]) 109 return datetime(*[ int(x) for x in ymd.split('-')+hms.split(':') ])
76 except ValueError: 110 except ValueError:
77 return date_or_None(obj) 111 return date_or_None(obj)
78 112
79 def timedelta_or_None(obj): 113 def timedelta_or_None(obj):
114 """Returns a TIME column as a timedelta object:
115
116 >>> timedelta_or_None('25:06:17')
117 datetime.timedelta(1, 3977)
118 >>> timedelta_or_None('-25:06:17')
119 datetime.timedelta(-2, 83177)
120
121 Illegal values are returned as None:
122
123 >>> timedelta_or_None('random crap') is None
124 True
125
126 Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
127 can accept values as (+|-)DD HH:MM:SS. The latter format will not
128 be parsed correctly by this function.
129 """
80 from math import modf 130 from math import modf
81 try: 131 try:
82 hours, minutes, seconds = obj.split(':') 132 hours, minutes, seconds = obj.split(':')
83 tdelta = timedelta(hours=int(hours), minutes=int(minutes), seconds=int(seconds), 133 tdelta = timedelta(
84 microseconds=int(modf(float(seconds))[0]*1000000)) 134 hours = int(hours),
135 minutes = int(minutes),
136 seconds = int(seconds),
137 microseconds = int(modf(float(seconds))[0]*1000000),
138 )
85 if hours < 0: 139 if hours < 0:
86 return -tdelta 140 return -tdelta
87 else: 141 else:
88 return tdelta 142 return tdelta
89 except ValueError: 143 except ValueError:
90 return None 144 return None
91 145
92 def time_or_None(obj): 146 def time_or_None(obj):
147 """Returns a TIME column as a time object:
148
149 >>> time_or_None('15:06:17')
150 datetime.time(15, 6, 17)
151
152 Illegal values are returned as None:
153
154 >>> time_or_None('-25:06:17') is None
155 True
156 >>> time_or_None('random crap') is None
157 True
158
159 Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
160 can accept values as (+|-)DD HH:MM:SS. The latter format will not
161 be parsed correctly by this function.
162
163 Also note that MySQL's TIME column corresponds more closely to
164 Python's timedelta and not time. However if you want TIME columns
165 to be treated as time-of-day and not a time offset, then you can
166 use set this function as the converter for FIELD_TYPE.TIME.
167 """
93 from math import modf 168 from math import modf
94 try: 169 try:
95 hour, minute, second = obj.split(':') 170 hour, minute, second = obj.split(':')
96 return time(hour=int(hour), minute=int(minute), second=int(second), 171 return time(hour=int(hour), minute=int(minute), second=int(second),
97 microsecond=int(modf(float(second))[0]*1000000)) 172 microsecond=int(modf(float(second))[0]*1000000))
98 except ValueError: 173 except ValueError:
99 return None 174 return None
100 175
101 def date_or_None(obj): 176 def date_or_None(obj):
102 try: 177 """Returns a DATE column as a date object:
103 return date(*[ int(x) for x in obj.split('-',2)]) 178
179 >>> date_or_None('2007-02-26')
180 datetime.date(2007, 2, 26)
181
182 Illegal values are returned as None:
183
184 >>> date_or_None('2007-02-31') is None
185 True
186 >>> date_or_None('0000-00-00') is None
187 True
188
189 """
190 try:
191 return date(*[ int(x) for x in obj.split('-', 2) ])
104 except ValueError: 192 except ValueError:
105 return None 193 return None
106 194
107 def datetime_to_sql(obj, conv): 195 def datetime_to_sql(obj, conv):
108 """Format a DateTime object as an ISO timestamp.""" 196 """Format a DateTime object as an ISO timestamp."""
109 return string_literal(format_TIMESTAMP(obj), conv) 197 return string_literal(datetime_to_str(obj), conv)
110 198
111 def timedelta_to_sql(obj, conv): 199 def timedelta_to_sql(obj, conv):
112 """Format a timedelta as an SQL literal. 200 """Format a timedelta as an SQL literal."""
113 201 return string_literal(timedelta_to_str(obj), conv)
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)
119 202
120 def mysql_timestamp_converter(timestamp): 203 def mysql_timestamp_converter(timestamp):
121 """Convert a MySQL TIMESTAMP to a Timestamp object. 204 """Convert a MySQL TIMESTAMP to a Timestamp object.
122 205
123 MySQL>4.1 returns TIMESTAMP in the same format as DATETIME: 206 MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:
124 207
125 >>> mysql_timestamp_converter('2007-02-25 22:32:17') 208 >>> mysql_timestamp_converter('2007-02-25 22:32:17')
126 datetime.datetime(2007, 2, 25, 22, 32, 17) 209 datetime.datetime(2007, 2, 25, 22, 32, 17)
127 210
128 MySQL<4.1 uses a big string of numbers: 211 MySQL < 4.1 uses a big string of numbers:
129 212
130 >>> mysql_timestamp_converter('20070225223217') 213 >>> mysql_timestamp_converter('20070225223217')
131 datetime.datetime(2007, 2, 25, 22, 32, 17) 214 datetime.datetime(2007, 2, 25, 22, 32, 17)
132 215
133 Illegal values are returned as None: 216 Illegal values are returned as None:
134 217
135 >>> print mysql_timestamp_converter('2007-02-31 22:32:17') 218 >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None
136 None 219 True
137 >>> print mysql_timestamp_converter('00000000000000') 220 >>> mysql_timestamp_converter('00000000000000') is None
138 None 221 True
139 222
140 """ 223 """
141 if timestamp[4] == '-': 224 if timestamp[4] == '-':
142 return datetime_or_None(timestamp) 225 return datetime_or_None(timestamp)
143 timestamp += "0"*(14-len(timestamp)) # padding 226 timestamp += "0"*(14-len(timestamp)) # padding