~openerp-commiter/openobject-addons/trunk-extra-addons

« back to all changes in this revision

Viewing changes to etl/lib/etl/connector/dbfpy/utils.py

  • Committer: qdp
  • Date: 2010-01-12 16:13:49 UTC
  • Revision ID: qdp-launchpad@tinyerp.com-20100112161349-gxa6mep6h43dzmyn
[IMP] ETL: added dbf connector and dbf_in component + example files

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""String utilities.
 
2
 
 
3
TODO:
 
4
  - allow strings in getDateTime routine;
 
5
"""
 
6
"""History (most recent first):
 
7
11-feb-2007 [als]   added INVALID_VALUE
 
8
10-feb-2007 [als]   allow date strings padded with spaces instead of zeroes
 
9
20-dec-2005 [yc]    handle long objects in getDate/getDateTime
 
10
16-dec-2005 [yc]    created from ``strutil`` module.
 
11
"""
 
12
 
 
13
__version__ = "$Revision: 1.4 $"[11:-2]
 
14
__date__ = "$Date: 2007/02/11 08:57:17 $"[7:-2]
 
15
 
 
16
import datetime
 
17
import time
 
18
 
 
19
 
 
20
def unzfill(str):
 
21
    """Return a string without ASCII NULs.
 
22
 
 
23
    This function searchers for the first NUL (ASCII 0) occurance
 
24
    and truncates string till that position.
 
25
 
 
26
    """
 
27
    try:
 
28
        return str[:str.index('\0')]
 
29
    except ValueError:
 
30
        return str
 
31
 
 
32
 
 
33
def getDate(date=None):
 
34
    """Return `datetime.date` instance.
 
35
 
 
36
    Type of the ``date`` argument could be one of the following:
 
37
        None:
 
38
            use current date value;
 
39
        datetime.date:
 
40
            this value will be returned;
 
41
        datetime.datetime:
 
42
            the result of the date.date() will be returned;
 
43
        string:
 
44
            assuming "%Y%m%d" or "%y%m%dd" format;
 
45
        number:
 
46
            assuming it's a timestamp (returned for example
 
47
            by the time.time() call;
 
48
        sequence:
 
49
            assuming (year, month, day, ...) sequence;
 
50
 
 
51
    Additionaly, if ``date`` has callable ``ticks`` attribute,
 
52
    it will be used and result of the called would be treated
 
53
    as a timestamp value.
 
54
 
 
55
    """
 
56
    if date is None:
 
57
        # use current value
 
58
        return datetime.date.today()
 
59
    if isinstance(date, datetime.date):
 
60
        return date
 
61
    if isinstance(date, datetime.datetime):
 
62
        return date.date()
 
63
    if isinstance(date, (int, long, float)):
 
64
        # date is a timestamp
 
65
        return datetime.date.fromtimestamp(date)
 
66
    if isinstance(date, basestring):
 
67
        date = date.replace(" ", "0")
 
68
        if len(date) == 6:
 
69
            # yymmdd
 
70
            return datetime.date(*time.strptime(date, "%y%m%d")[:3])
 
71
        # yyyymmdd
 
72
        return datetime.date(*time.strptime(date, "%Y%m%d")[:3])
 
73
    if hasattr(date, "__getitem__"):
 
74
        # a sequence (assuming date/time tuple)
 
75
        return datetime.date(*date[:3])
 
76
    return datetime.date.fromtimestamp(date.ticks())
 
77
 
 
78
 
 
79
def getDateTime(value=None):
 
80
    """Return `datetime.datetime` instance.
 
81
 
 
82
    Type of the ``value`` argument could be one of the following:
 
83
        None:
 
84
            use current date value;
 
85
        datetime.date:
 
86
            result will be converted to the `datetime.datetime` instance
 
87
            using midnight;
 
88
        datetime.datetime:
 
89
            ``value`` will be returned as is;
 
90
        string:
 
91
            *** CURRENTLY NOT SUPPORTED ***;
 
92
        number:
 
93
            assuming it's a timestamp (returned for example
 
94
            by the time.time() call;
 
95
        sequence:
 
96
            assuming (year, month, day, ...) sequence;
 
97
 
 
98
    Additionaly, if ``value`` has callable ``ticks`` attribute,
 
99
    it will be used and result of the called would be treated
 
100
    as a timestamp value.
 
101
 
 
102
    """
 
103
    if value is None:
 
104
        # use current value
 
105
        return datetime.datetime.today()
 
106
    if isinstance(value, datetime.datetime):
 
107
        return value
 
108
    if isinstance(value, datetime.date):
 
109
        return datetime.datetime.fromordinal(value.toordinal())
 
110
    if isinstance(value, (int, long, float)):
 
111
        # value is a timestamp
 
112
        return datetime.datetime.fromtimestamp(value)
 
113
    if isinstance(value, basestring):
 
114
        raise NotImplementedError("Strings aren't currently implemented")
 
115
    if hasattr(value, "__getitem__"):
 
116
        # a sequence (assuming date/time tuple)
 
117
        return datetime.datetime(*tuple(value)[:6])
 
118
    return datetime.datetime.fromtimestamp(value.ticks())
 
119
 
 
120
 
 
121
class classproperty(property):
 
122
    """Works in the same way as a ``property``, but for the classes."""
 
123
 
 
124
    def __get__(self, obj, cls):
 
125
        return self.fget(cls)
 
126
 
 
127
 
 
128
class _InvalidValue(object):
 
129
 
 
130
    """Value returned from DBF records when field validation fails
 
131
 
 
132
    The value is not equal to anything except for itself
 
133
    and equal to all empty values: None, 0, empty string etc.
 
134
    In other words, invalid value is equal to None and not equal
 
135
    to None at the same time.
 
136
 
 
137
    This value yields zero upon explicit conversion to a number type,
 
138
    empty string for string types, and False for boolean.
 
139
 
 
140
    """
 
141
 
 
142
    def __eq__(self, other):
 
143
        return not other
 
144
 
 
145
    def __ne__(self, other):
 
146
        return not (other is self)
 
147
 
 
148
    def __nonzero__(self):
 
149
        return False
 
150
 
 
151
    def __int__(self):
 
152
        return 0
 
153
    __long__ = __int__
 
154
 
 
155
    def __float__(self):
 
156
        return 0.0
 
157
 
 
158
    def __str__(self):
 
159
        return ""
 
160
 
 
161
    def __unicode__(self):
 
162
        return u""
 
163
 
 
164
    def __repr__(self):
 
165
        return "<INVALID>"
 
166
 
 
167
# invalid value is a constant singleton
 
168
INVALID_VALUE = _InvalidValue()
 
169
 
 
170
# vim: set et sts=4 sw=4 :