Source

django-timedelta-field / timedelta / helpers.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import re
import datetime
from decimal import Decimal
from itertools import product


language_sets = {}

language_sets['en'] = {
    'ignore': re.compile(r'^(and)$', re.IGNORECASE),
    'weeks': re.compile(r'^(weeks?|wks?|w)$', re.IGNORECASE),
    'days': re.compile(r'^(days?|d)$', re.IGNORECASE),
    'hours': re.compile(r'^(hours?|hrs|hr?)$', re.IGNORECASE),
    'minutes': re.compile(r'^(minutes?|mins?|m)$', re.IGNORECASE),
    'seconds': re.compile(r'^(seconds?|secs?|s)$', re.IGNORECASE),
}

language_sets['de'] = {
    'ignore': re.compile(r'^(und)$', re.IGNORECASE),
    'weeks': re.compile(r'^(woche?|ws?|w)$', re.IGNORECASE),
    'days': re.compile(r'^(tag?|ts?)$', re.IGNORECASE),
    'hours': re.compile(r'^(stunden?|ss?|hr?)$', re.IGNORECASE),
    'minutes': re.compile(r'^(minuten?|mins?|m)$', re.IGNORECASE),
    'seconds': re.compile(r'^(Sekunden?|seks?|s)$', re.IGNORECASE),
}

bits = ['ignore', 'weeks', 'days', 'hours', 'minutes', 'seconds']


def nice_repr(timedelta, display="long", sep=", "):
    """
    Turns a datetime.timedelta object into a nice string repr.
    
    display can be "minimal", "short" or "long" [default].
    
    >>> from datetime import timedelta as td
    >>> nice_repr(td(days=1, hours=2, minutes=3, seconds=4))
    '1 day, 2 hours, 3 minutes, 4 seconds'
    >>> nice_repr(td(days=1, seconds=1), "minimal")
    '1d, 1s'
    """
    
    assert isinstance(timedelta, datetime.timedelta), "First argument must be a timedelta."
    
    result = []
    
    weeks = timedelta.days / 7
    days = timedelta.days % 7
    hours = timedelta.seconds / 3600
    minutes = (timedelta.seconds % 3600) / 60
    seconds = timedelta.seconds % 60
    
    if display == "sql":
        days += weeks * 7
        return "%i %02i:%02i:%02i" % (days, hours, minutes, seconds)
    elif display == 'minimal':
        words = ["w", "d", "h", "m", "s"]
    elif display == 'short':
        words = [" wks", " days", " hrs", " min", " sec"]
    else:
        words = [" weeks", " days", " hours", " minutes", " seconds"]
    
    values = [weeks, days, hours, minutes, seconds]
    
    for i in range(len(values)):
        if values[i]:
            if values[i] == 1 and len(words[i]) > 1:
                result.append("%i%s" % (values[i], words[i].rstrip('s')))
            else:
                result.append("%i%s" % (values[i], words[i]))
    
    return sep.join(result)

def iso8601_repr(timedelta):
    """
    Represent a timedelta as an ISO8601 duration.
    http://en.wikipedia.org/wiki/ISO_8601#Durations

    >>> from datetime import timedelta as td
    >>> iso8601_repr(td(days=1, hours=2, minutes=3, seconds=4))
    'P1DT2H3M4S'
    """
    years = timedelta.days / 365
    weeks = (timedelta.days % 365) / 7
    days = timedelta.days % 7

    hours = timedelta.seconds / 3600
    minutes = (timedelta.seconds % 3600) / 60
    seconds = timedelta.seconds % 60

    formatting = (
        ('P', (
            ('Y', years),
            ('W', weeks),
            ('D', days),
        )),
        ('T', (
            ('H', hours),
            ('M', minutes),
            ('S', seconds),
        )),
      )

    result = []
    for category, subcats in formatting:
        result += category
        for format, value in subcats:
            if value:
                result.append('%d%c' % (value, format))

    return "".join(result)


def parse(time_string, languages=['en']):
    """
    Parse a string into a timedelta object.
    
    >>> parse("1 day")
    datetime.timedelta(1)
    >>> parse("2 days")
    datetime.timedelta(2)
    >>> parse("1 d")
    datetime.timedelta(1)
    >>> parse("1 hour")
    datetime.timedelta(0, 3600)
    >>> parse("1 hours")
    datetime.timedelta(0, 3600)
    >>> parse("1 hr")
    datetime.timedelta(0, 3600)
    >>> parse("1 hrs")
    datetime.timedelta(0, 3600)
    >>> parse("1h")
    datetime.timedelta(0, 3600)
    >>> parse("1wk")
    datetime.timedelta(7)
    >>> parse("1 week")
    datetime.timedelta(7)
    >>> parse("1 weeks")
    datetime.timedelta(7)
    >>> parse("2 wks")
    datetime.timedelta(14)
    >>> parse("1 sec")
    datetime.timedelta(0, 1)
    >>> parse("1 secs")
    datetime.timedelta(0, 1)
    >>> parse("1 s")
    datetime.timedelta(0, 1)
    >>> parse("1 second")
    datetime.timedelta(0, 1)
    >>> parse("1 seconds")
    datetime.timedelta(0, 1)
    >>> parse("1 minute")
    datetime.timedelta(0, 60)
    >>> parse("1 min")
    datetime.timedelta(0, 60)
    >>> parse("1 m")
    datetime.timedelta(0, 60)
    >>> parse("1 minutes")
    datetime.timedelta(0, 60)
    >>> parse("1 mins")
    datetime.timedelta(0, 60)
    >>> parse("2 ws")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '2 ws' at '2 ws'
    >>> parse("2 ds")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '2 ds' at '2 ds'
    >>> parse("2 hs")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '2 hs' at '2 hs'
    >>> parse("2 ms")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '2 ms' at '2 ms'
    >>> parse("2 ss")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '2 ss' at '2 ss'
    >>> parse("1 day, 2 ss")
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '1 day, 2 ss' at '2 ss'
    >>> parse("")
    Traceback (most recent call last):
    ...
    TypeError: '' is not a valid time interval
    
    >>> parse("1 minuten", ['de'])
    datetime.timedelta(0, 60)
    >>> parse("2 woche", ['de'])
    datetime.timedelta(14)
    >>> parse("1 day", ['de'])
    Traceback (most recent call last):
    ...
    TypeError: Could not parse remaining time string: '1 day' at '1 day'
    """
    
    if not time_string:
        raise TypeError('{0!r} is not a valid time interval'.format(time_string))
    
    sets = []
    for language in languages:
        language_set = language_sets[language]
        sets.append(language_set)
    
    splitter = re.compile(r'^\s*(?P<count>-?(?:\d*\.)?\d+)?\s*(?P<type>\w+)(?:,\s*|\s+|$)')
    
    matched_bits = splitter.findall(time_string)
    kwargs = {}
    
    original_time_string = time_string
    
    while time_string:
        match = splitter.match(time_string)
    
        if not match:
            raise TypeError("Could not parse remaining time string: {0!r} at {1!r}".format(original_time_string, time_string[:20]))
    
        count, time_type = match.groups()
        found = False
        language_set_bit_iter = product(sets, bits)
    
        try:
            while not found:
                language_set, bit = next(language_set_bit_iter)
                type_matcher = language_set[bit]
                if not type_matcher.match(time_type):
                    continue
                if bit in kwargs and time_type != 'ignore':
                    raise ValueError(
                        "Time type '{0}' specified more than once".format(bit))
    
                kwargs[bit] = float(count or '1')
                found = True
    
        except StopIteration:
            raise TypeError("Could not parse remaining time string: {0!r} at {1!r}".format(original_time_string, time_string[:20]))
    
        time_string = time_string[match.end():]
    
    kwargs.pop('ignore', None)
    
    return datetime.timedelta(**kwargs)


def divide(obj1, obj2, as_float=False):
    """
    Allows for the division of timedeltas by other timedeltas, or by
    floats/Decimals
    
    >>> from datetime import timedelta as td
    >>> divide(td(1), td(1))
    1
    >>> divide(td(2), td(1))
    2
    >>> divide(td(32), 16)
    datetime.timedelta(2)
    """
    assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
    assert isinstance(obj2, (datetime.timedelta, int, float, Decimal)), "Second argument must be a timedelta or number"
    
    sec1 = obj1.days * 86400 + obj1.seconds
    if isinstance(obj2, datetime.timedelta):
        sec2 = obj2.days * 86400 + obj2.seconds
        if as_float:
            sec1 *= 1.0
        return sec1 / sec2
    else:
        if as_float:
            assert None, "as_float=True is inappropriate when dividing timedelta by a number."
        secs = sec1 / obj2
        if isinstance(secs, Decimal):
            secs = float(secs)
        return datetime.timedelta(seconds=secs)

def modulo(obj1, obj2):
    """
    Allows for remainder division of timedelta by timedelta or integer.
    
    >>> from datetime import timedelta as td
    >>> modulo(td(5), td(2))
    datetime.timedelta(1)
    >>> modulo(td(6), td(3))
    datetime.timedelta(0)
    >>> modulo(td(15), 4 * 3600 * 24)
    datetime.timedelta(3)
    """
    assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
    assert isinstance(obj2, (datetime.timedelta, int)), "Second argument must be a timedelta or int."
    
    sec1 = obj1.days * 86400 + obj1.seconds
    if isinstance(obj2, datetime.timedelta):
        sec2 = obj2.days * 86400 + obj2.seconds
        return datetime.timedelta(seconds=sec1 % sec2)
    else:
        return datetime.timedelta(seconds=(sec1 % obj2))
    
def percentage(obj1, obj2):
    """
    What percentage of obj2 is obj1? We want the answer as a float.
    >>> percentage(datetime.timedelta(2), datetime.timedelta(4))
    50.0
    """
    assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
    assert isinstance(obj2, datetime.timedelta), "Second argument must be a timedelta."
    
    return divide(obj1 * 100, obj2, as_float=True)

def decimal_percentage(obj1, obj2):
    """
    >>> decimal_percentage(datetime.timedelta(2), datetime.timedelta(4))
    Decimal('50.0')
    """
    return Decimal(str(percentage(obj1, obj2)))
    
    
def multiply(obj, val):
    """
    Allows for the multiplication of timedeltas by float values.
    >>> multiply(datetime.timedelta(seconds=20), 1.5)
    datetime.timedelta(0, 30)
    """
    
    assert isinstance(obj, datetime.timedelta), "First argument must be a timedelta."
    assert isinstance(val, (int, float, Decimal)), "Second argument must be a number."
    
    sec = obj.days * 86400 + obj.seconds
    sec *= val
    if isinstance(sec, Decimal):
        sec = float(sec)
    return datetime.timedelta(seconds=sec)


def round_to_nearest(obj, timedelta):
    """
    The obj is rounded to the nearest whole number of timedeltas.
    
    obj can be a timedelta, datetime or time object.
    
    >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(1))
    datetime.datetime(2012, 1, 1, 0, 0)
    >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(hours=1))
    datetime.datetime(2012, 1, 1, 10, 0)
    >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(minutes=15))
    datetime.datetime(2012, 1, 1, 9, 45)
    >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(minutes=1))
    datetime.datetime(2012, 1, 1, 9, 43)
    """
    
    assert isinstance(obj, (datetime.datetime, datetime.timedelta, datetime.time)), "First argument must be datetime, time or timedelta."
    assert isinstance(timedelta, datetime.timedelta), "Second argument must be a timedelta."
    
    time_only = False
    if isinstance(obj, datetime.timedelta):
        counter = datetime.timedelta(0)
    elif isinstance(obj, datetime.datetime):
        counter = datetime.datetime.combine(obj.date(), datetime.time(0, tzinfo=obj.tzinfo))
    elif isinstance(obj, datetime.time):
        counter = datetime.datetime.combine(datetime.date.today(), datetime.time(0, tzinfo=obj.tzinfo))
        obj = datetime.datetime.combine(datetime.date.today(), obj)
        time_only = True
    
    diff = abs(obj - counter)
    while counter < obj:
        old_diff = diff
        counter += timedelta
        diff = abs(obj - counter)
    
    if counter == obj:
        result = obj
    elif diff <= old_diff:
        result = counter
    else:
        result = counter - timedelta
    
    if time_only:
        return result.time()
    else:
        return result

def decimal_hours(timedelta, decimal_places=None):
    """
    Return a decimal value of the number of hours that this timedelta
    object refers to.
    """
    hours = Decimal(timedelta.days*24) + Decimal(timedelta.seconds) / 3600
    if decimal_places:
        return hours.quantize(Decimal(str(10**-decimal_places)))
    return hours

def week_containing(date):
    if date.weekday():
        date -= datetime.timedelta(date.weekday())
    
    return date, date + datetime.timedelta(6)

try:
    datetime.timedelta().total_seconds
    def total_seconds(timedelta):
        return timedelta.total_seconds()
except AttributeError:
    def total_seconds(timedelta):
        """
        Python < 2.7 does not have datetime.timedelta.total_seconds
        """
        return timedelta.days * 86400 + timedelta.seconds

if __name__ == "__main__":
    import doctest
    doctest.testmod()