comparison MySQLdb/times.py @ 0:e48810735f11 MySQLdb

Copying 1.2.1 to be the new trunk
author adustman
date Sun, 02 Apr 2006 18:20:53 +0000
parents
children b5a377255eea
comparison
equal deleted inserted replaced
-1:000000000000 0:e48810735f11
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_TIMESTAMP(d):
34 return d.strftime("%Y-%m-%d %H:%M:%S")
35
36
37 def DateTime_or_None(s):
38 if ' ' in s:
39 sep = ' '
40 elif 'T' in s:
41 sep = 'T'
42 else:
43 return Date_or_None(s)
44
45 try:
46 d, t = s.split(sep, 1)
47 return datetime(*[ int(x) for x in d.split('-')+t.split(':') ])
48 except:
49 return Date_or_None(s)
50
51 def TimeDelta_or_None(s):
52 from math import modf
53 try:
54 h, m, s = s.split(':')
55 td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)),
56 microseconds=int(modf(float(s))[0]*1000000))
57 if h < 0:
58 return -td
59 else:
60 return td
61 except:
62 return None
63
64 def Time_or_None(s):
65 from math import modf
66 try:
67 h, m, s = s.split(':')
68 return time(hour=int(h), minute=int(m), second=int(float(s)),
69 microsecond=int(modf(float(s))[0]*1000000))
70 except:
71 return None
72
73 def Date_or_None(s):
74 try: return date(*[ int(x) for x in s.split('-',2)])
75 except: return None
76
77 def DateTime2literal(d, c):
78 """Format a DateTime object as an ISO timestamp."""
79 return string_literal(format_TIMESTAMP(d),c)
80
81 def DateTimeDelta2literal(d, c):
82 """Format a DateTimeDelta object as a time."""
83 return string_literal(format_TIME(d),c)
84
85 def mysql_timestamp_converter(s):
86 """Convert a MySQL TIMESTAMP to a Timestamp object."""
87 # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
88 if s[4] == '-': return DateTime_or_None(s)
89 s = s + "0"*(14-len(s)) # padding
90 parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
91 s[8:10],s[10:12],s[12:14])))
92 try: return Timestamp(*parts)
93 except: return None