116
116
datetime.timedelta(0, 60)
117
117
>>> rfc3339_duration_to_delta("PT60M")
118
118
datetime.timedelta(0, 3600)
119
>>> rfc3339_duration_to_delta("P60M")
120
datetime.timedelta(1680)
121
119
>>> rfc3339_duration_to_delta("PT24H")
122
120
datetime.timedelta(1)
123
121
>>> rfc3339_duration_to_delta("P1W")
126
124
datetime.timedelta(0, 330)
127
125
>>> rfc3339_duration_to_delta("P1DT3M20S")
128
126
datetime.timedelta(1, 200)
129
>>> # Can not be empty:
130
>>> rfc3339_duration_to_delta("")
131
Traceback (most recent call last):
133
ValueError: Invalid RFC 3339 duration: u''
134
>>> # Must start with "P":
135
>>> rfc3339_duration_to_delta("1D")
136
Traceback (most recent call last):
138
ValueError: Invalid RFC 3339 duration: u'1D'
139
>>> # Must use correct order
140
>>> rfc3339_duration_to_delta("PT1S2M")
141
Traceback (most recent call last):
143
ValueError: Invalid RFC 3339 duration: u'PT1S2M'
144
>>> # Time needs time marker
145
>>> rfc3339_duration_to_delta("P1H2S")
146
Traceback (most recent call last):
148
ValueError: Invalid RFC 3339 duration: u'P1H2S'
149
>>> # Weeks can not be combined with anything else
150
>>> rfc3339_duration_to_delta("P1D2W")
151
Traceback (most recent call last):
153
ValueError: Invalid RFC 3339 duration: u'P1D2W'
154
>>> rfc3339_duration_to_delta("P2W2H")
155
Traceback (most recent call last):
157
ValueError: Invalid RFC 3339 duration: u'P2W2H'
160
129
# Parsing an RFC 3339 duration with regular expressions is not
240
209
def string_to_delta(interval):
241
210
"""Parse a string and return a datetime.timedelta
212
>>> string_to_delta('7d')
213
datetime.timedelta(7)
214
>>> string_to_delta('60s')
215
datetime.timedelta(0, 60)
216
>>> string_to_delta('60m')
217
datetime.timedelta(0, 3600)
218
>>> string_to_delta('24h')
219
datetime.timedelta(1)
220
>>> string_to_delta('1w')
221
datetime.timedelta(7)
222
>>> string_to_delta('5m 30s')
223
datetime.timedelta(0, 330)
245
227
return rfc3339_duration_to_delta(interval)
246
except ValueError as e:
247
log.warning("%s - Parsing as pre-1.6.1 interval instead",
249
return parse_pre_1_6_1_interval(interval)
252
def parse_pre_1_6_1_interval(interval):
253
"""Parse an interval string as documented by Mandos before 1.6.1, and
254
return a datetime.timedelta
255
>>> parse_pre_1_6_1_interval('7d')
256
datetime.timedelta(7)
257
>>> parse_pre_1_6_1_interval('60s')
258
datetime.timedelta(0, 60)
259
>>> parse_pre_1_6_1_interval('60m')
260
datetime.timedelta(0, 3600)
261
>>> parse_pre_1_6_1_interval('24h')
262
datetime.timedelta(1)
263
>>> parse_pre_1_6_1_interval('1w')
264
datetime.timedelta(7)
265
>>> parse_pre_1_6_1_interval('5m 30s')
266
datetime.timedelta(0, 330)
267
>>> parse_pre_1_6_1_interval('')
268
datetime.timedelta(0)
269
>>> # Ignore unknown characters, allow any order and repetitions
270
>>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
271
datetime.timedelta(2, 480, 18000)
275
231
value = datetime.timedelta(0)
276
232
regexp = re.compile(r"(\d+)([dsmhw]?)")