Package MySQLdb :: Module times
[hide private]
[frames] | no frames]

Source Code for Module MySQLdb.times

  1  """times module 
  2   
  3  This module provides some Date and Time classes for dealing with MySQL data. 
  4   
  5  Use Python datetime module to handle date and time columns.""" 
  6   
  7  from time import localtime 
  8  from datetime import date, datetime, time, timedelta 
  9  from _mysql import string_literal 
 10   
 11  Date = date 
 12  Time = time 
 13  TimeDelta = timedelta 
 14  Timestamp = datetime 
 15   
 16  DateTimeDeltaType = timedelta 
 17  DateTimeType = datetime 
 18   
19 -def DateFromTicks(ticks):
20 """Convert UNIX ticks into a date instance.""" 21 return date(*localtime(ticks)[:3])
22
23 -def TimeFromTicks(ticks):
24 """Convert UNIX ticks into a time instance.""" 25 return time(*localtime(ticks)[3:6])
26
27 -def TimestampFromTicks(ticks):
28 """Convert UNIX ticks into a datetime instance.""" 29 return datetime(*localtime(ticks)[:6])
30 31 format_TIME = format_DATE = str 32
33 -def format_TIMEDELTA(v):
34 seconds = int(v.seconds) % 60 35 minutes = int(v.seconds / 60) % 60 36 hours = int(v.seconds / 3600) % 24 37 return '%d %d:%d:%d' % (v.days, hours, minutes, seconds)
38
39 -def format_TIMESTAMP(d):
40 return d.strftime("%Y-%m-%d %H:%M:%S")
41 42
43 -def DateTime_or_None(s):
44 if ' ' in s: 45 sep = ' ' 46 elif 'T' in s: 47 sep = 'T' 48 else: 49 return Date_or_None(s) 50 51 try: 52 d, t = s.split(sep, 1) 53 return datetime(*[ int(x) for x in d.split('-')+t.split(':') ]) 54 except: 55 return Date_or_None(s)
56
57 -def TimeDelta_or_None(s):
58 from math import modf 59 try: 60 h, m, s = s.split(':') 61 td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)), 62 microseconds=int(modf(float(s))[0]*1000000)) 63 if h < 0: 64 return -td 65 else: 66 return td 67 except: 68 return None
69
70 -def Time_or_None(s):
71 from math import modf 72 try: 73 h, m, s = s.split(':') 74 return time(hour=int(h), minute=int(m), second=int(float(s)), 75 microsecond=int(modf(float(s))[0]*1000000)) 76 except: 77 return None
78
79 -def Date_or_None(s):
80 try: return date(*[ int(x) for x in s.split('-',2)]) 81 except: return None
82
83 -def DateTime2literal(d, c):
84 """Format a DateTime object as an ISO timestamp.""" 85 return string_literal(format_TIMESTAMP(d),c)
86
87 -def DateTimeDelta2literal(d, c):
88 """Format a DateTimeDelta object as a time.""" 89 return string_literal(format_TIMEDELTA(d),c)
90
91 -def mysql_timestamp_converter(s):
92 """Convert a MySQL TIMESTAMP to a Timestamp object.""" 93 # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME 94 if s[4] == '-': return DateTime_or_None(s) 95 s = s + "0"*(14-len(s)) # padding 96 parts = map(int, filter(None, (s[:4],s[4:6],s[6:8], 97 s[8:10],s[10:12],s[12:14]))) 98 try: return Timestamp(*parts) 99 except: return None
100