Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

# -*- coding: UTF-8 -*- 

# Copyright 2012-2015 Luc Saffre 

# License: BSD (see file COPYING for details) 

 

r""" 

A :class:`Duration` is a Decimal expressed in ``hh:mm`` format. 

A :class:`Percentage` is a Decimal expressed in ``x%`` format. 

 

Usage examples: 

 

The `parse` function 

==================== 

 

>>> parse('1') 

Decimal('1') 

>>> parse('1:15') 

Duration('1:15') 

>>> parse('33%') 

Percentage('33%') 

 

>>> lines = [] 

>>> lines.append('repr(x)              str(x)    x*3  x*100') 

>>> lines.append('------------------- ------- ------ ------') 

>>> for s in '2', '2.5', '33%', '2:30', '0:20': 

...     v = parse(s) 

...     lines.append("%-20s %6s %6s %6s" % (repr(v), v, v*3, v*100)) 

>>> print '\n'.join(lines) 

repr(x)              str(x)    x*3  x*100 

------------------- ------- ------ ------ 

Decimal('2')              2      6    200 

Decimal('2.5')          2.5    7.5  250.0 

Percentage('33%')       33%   0.99  33.00 

Duration('2:30')       2:30   7:30 250:00 

Duration('0:20')       0:20   1:00  33:20 

 

Formatting 

========== 

 

>>> print Duration("0.33334") 

0:20 

>>> print Duration("2.50") 

2:30 

 

Decimal separator 

================= 

 

Both period and comma are accepted as decimal separator: 

 

>>> parse('1.5') 

Decimal('1.5') 

>>> parse('1,5') 

Decimal('1.5') 

 

But you may not use both at the same time: 

 

>>> parse('1,000.50') 

Traceback (most recent call last): 

... 

Exception: Invalid decimal value '1,000.50' 

 

 

""" 

from __future__ import division 

from builtins import str 

from past.builtins import basestring 

from past.utils import old_div 

 

import datetime 

from decimal import Decimal 

 

DEC2HOUR = old_div(Decimal(1), Decimal(60)) 

 

 

class Quantity(Decimal): 

 

    def __repr__(self): 

        return "%s('%s')" % (self.__class__.__name__, str(self)) 

 

    def __add__(self, *args, **kw): 

        return self.__class__(Decimal.__add__(self, *args, **kw)) 

    __radd__ = __add__ 

 

    def __truediv__(self, *args, **kw): 

        return self.__class__(Decimal.__truediv__(self, *args, **kw)) 

    __rtruediv__ = __truediv__ 

    __div__ = __truediv__ 

    __rdiv__ = __rtruediv__ 

 

    def __mul__(self, *args, **kw): 

        return self.__class__(Decimal.__mul__(self, *args, **kw)) 

    __rmul__ = __mul__ 

 

 

class Percentage(Quantity): 

 

    def __new__(cls, value="0", context=None): 

        if isinstance(value, basestring) and value.endswith('%'): 

            self = Decimal.__new__( 

                Percentage, old_div(Decimal(value[:-1]), 100), context) 

            self._value = value 

            return self 

        #~ raise Exception("Invalid Percentage %r" % value) 

        return cls.__new__(Quantity, value, context) 

 

    def __str__(self): 

        return self._value 

 

 

class Duration(Quantity): 

    """A duration, expressed in `hours:minutes`. 

 

    >>> print Duration('1') 

    1:00 

    >>> print Duration('2.5') 

    2:30 

    >>> print Duration('2.50') 

    2:30 

     

    >>> print Duration('1:00') 

    1:00 

    >>> print Duration('1:30') 

    1:30 

    >>> print Duration('1:55') 

    1:55 

     

    >>> print Duration('1:45') * 2 

    3:30 

    >>> print Duration('1:55') * 2 

    3:50 

     

    >>> print Duration('0:45') / 3 

    0:15 

     

    >>> print Duration('0:49') / 10 

    0:05 

     

    >>> print Duration('1:30') * 2 

    3:00 

    >>> print Duration('0:03') * 10 

    0:30 

    >>> print Duration('0:01') * 60 

    1:00 

    >>> print Duration('0:01') * 6000 

    100:00 

     

    >>> print Duration('1:55') + Duration('0:05') 

    2:00 

    >>> print Duration('1:55') + Duration('0:10') 

    2:05 

     

    >>> print Duration('1:55') - Duration('0:10') 

    1:45 

    >>> print Duration('1:05') - Duration('0:10') 

    0:55 

     

    >>> print Duration(datetime.timedelta(0)) 

    0:00 

    >>> print Duration(datetime.timedelta(0, hours=10)) 

    10:00 

    >>> print Duration(datetime.timedelta(0, minutes=10)) 

    0:10 

 

    A duration can be more than 24 hours, and in that case (unlike 

    :class:`datetime.datetime`) it is still represented using 

    `hhhh.mm`: 

 

    >>> print Duration(datetime.timedelta(hours=25)) 

    25:00 

 

    >>> print Duration(datetime.timedelta(days=128)) 

    3072:00 

 

    """ 

 

    def __new__(cls, value="0", context=None): 

        if isinstance(value, basestring): 

            if ':' in value: 

                h, m = value.split(':') 

                value = Decimal(h) + Decimal(m) * DEC2HOUR 

        elif isinstance(value, datetime.timedelta): 

            hours = 0 

            if value.days != 0: 

                hours += value.days * 24 

                value = datetime.timedelta(seconds=value.seconds) 

            a = str(value).split(':')[:2] 

            hours += int(a[0]) 

            minutes = int(a[1]) 

            return cls('{0}:{1}'.format(hours, minutes)) 

            # return cls(':'.join(a)) 

        self = Decimal.__new__(Duration, value, context) 

        return self 

 

    def __str__(self): 

        minutes = old_div((self - int(self)), DEC2HOUR) 

        return '%d:%02d' % ( 

            int(self), 

            minutes.to_integral()) 

 

 

def parse(s): 

    """ 

    """ 

    if not isinstance(s, basestring): 

        raise Exception("Expected a string, got %r" % s) 

    if ':' in s: 

        return Duration(s) 

    # if '/' in s: 

    #     return Fraction(s) 

    if s.endswith('%'): 

        return Percentage(s) 

    return parse_decimal(s) 

 

 

def parse_decimal(s): 

    if '.' in s and ',' in s: 

        raise Exception("Invalid decimal value %r" % s) 

    s = s.replace(',', '.') 

    return Decimal(s) 

 

 

def _test(): 

    import doctest 

    doctest.testmod() 

 

if __name__ == "__main__": 

    _test()