summaryrefslogtreecommitdiffhomepage
path: root/libs/aniso8601/interval.py
blob: cd0184c6b839bd7e5bf916e41ac155a239d0f33a (plain)
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
# -*- coding: utf-8 -*-

# Copyright (c) 2021, Brandon Nielsen
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license.  See the LICENSE file for details.

from aniso8601.builders import DatetimeTuple, DateTuple, TupleBuilder
from aniso8601.builders.python import PythonTimeBuilder
from aniso8601.compat import is_string
from aniso8601.date import parse_date
from aniso8601.duration import parse_duration
from aniso8601.exceptions import ISOFormatError
from aniso8601.resolution import IntervalResolution
from aniso8601.time import parse_datetime, parse_time


def get_interval_resolution(
    isointervalstr, intervaldelimiter="/", datetimedelimiter="T"
):
    isointervaltuple = parse_interval(
        isointervalstr,
        intervaldelimiter=intervaldelimiter,
        datetimedelimiter=datetimedelimiter,
        builder=TupleBuilder,
    )

    return _get_interval_resolution(isointervaltuple)


def get_repeating_interval_resolution(
    isointervalstr, intervaldelimiter="/", datetimedelimiter="T"
):
    repeatingintervaltuple = parse_repeating_interval(
        isointervalstr,
        intervaldelimiter=intervaldelimiter,
        datetimedelimiter=datetimedelimiter,
        builder=TupleBuilder,
    )

    return _get_interval_resolution(repeatingintervaltuple.interval)


def _get_interval_resolution(intervaltuple):
    if intervaltuple.start is not None and intervaltuple.end is not None:
        return max(
            _get_interval_component_resolution(intervaltuple.start),
            _get_interval_component_resolution(intervaltuple.end),
        )

    if intervaltuple.start is not None and intervaltuple.duration is not None:
        return max(
            _get_interval_component_resolution(intervaltuple.start),
            _get_interval_component_resolution(intervaltuple.duration),
        )

    return max(
        _get_interval_component_resolution(intervaltuple.end),
        _get_interval_component_resolution(intervaltuple.duration),
    )


def _get_interval_component_resolution(componenttuple):
    if type(componenttuple) is DateTuple:
        if componenttuple.DDD is not None:
            # YYYY-DDD
            # YYYYDDD
            return IntervalResolution.Ordinal

        if componenttuple.D is not None:
            # YYYY-Www-D
            # YYYYWwwD
            return IntervalResolution.Weekday

        if componenttuple.Www is not None:
            # YYYY-Www
            # YYYYWww
            return IntervalResolution.Week

        if componenttuple.DD is not None:
            # YYYY-MM-DD
            # YYYYMMDD
            return IntervalResolution.Day

        if componenttuple.MM is not None:
            # YYYY-MM
            return IntervalResolution.Month

        # Y[YYY]
        return IntervalResolution.Year
    elif type(componenttuple) is DatetimeTuple:
        # Datetime
        if componenttuple.time.ss is not None:
            return IntervalResolution.Seconds

        if componenttuple.time.mm is not None:
            return IntervalResolution.Minutes

        return IntervalResolution.Hours

    # Duration
    if componenttuple.TnS is not None:
        return IntervalResolution.Seconds

    if componenttuple.TnM is not None:
        return IntervalResolution.Minutes

    if componenttuple.TnH is not None:
        return IntervalResolution.Hours

    if componenttuple.PnD is not None:
        return IntervalResolution.Day

    if componenttuple.PnW is not None:
        return IntervalResolution.Week

    if componenttuple.PnM is not None:
        return IntervalResolution.Month

    return IntervalResolution.Year


def parse_interval(
    isointervalstr,
    intervaldelimiter="/",
    datetimedelimiter="T",
    builder=PythonTimeBuilder,
):
    # Given a string representing an ISO 8601 interval, return an
    # interval built by the given builder. Valid formats are:
    #
    # <start>/<end>
    # <start>/<duration>
    # <duration>/<end>
    #
    # The <start> and <end> values can represent dates, or datetimes,
    # not times.
    #
    # The format:
    #
    # <duration>
    #
    # Is expressly not supported as there is no way to provide the additional
    # required context.

    if is_string(isointervalstr) is False:
        raise ValueError("Interval must be string.")

    if len(isointervalstr) == 0:
        raise ISOFormatError("Interval string is empty.")

    if isointervalstr[0] == "R":
        raise ISOFormatError(
            "ISO 8601 repeating intervals must be parsed "
            "with parse_repeating_interval."
        )

    intervaldelimitercount = isointervalstr.count(intervaldelimiter)

    if intervaldelimitercount == 0:
        raise ISOFormatError(
            'Interval delimiter "{0}" is not in interval '
            'string "{1}".'.format(intervaldelimiter, isointervalstr)
        )

    if intervaldelimitercount > 1:
        raise ISOFormatError(
            "{0} is not a valid ISO 8601 interval".format(isointervalstr)
        )

    return _parse_interval(
        isointervalstr, builder, intervaldelimiter, datetimedelimiter
    )


def parse_repeating_interval(
    isointervalstr,
    intervaldelimiter="/",
    datetimedelimiter="T",
    builder=PythonTimeBuilder,
):
    # Given a string representing an ISO 8601 interval repeating, return an
    # interval built by the given builder. Valid formats are:
    #
    # Rnn/<interval>
    # R/<interval>

    if not isinstance(isointervalstr, str):
        raise ValueError("Interval must be string.")

    if len(isointervalstr) == 0:
        raise ISOFormatError("Repeating interval string is empty.")

    if isointervalstr[0] != "R":
        raise ISOFormatError("ISO 8601 repeating interval must start " "with an R.")

    if intervaldelimiter not in isointervalstr:
        raise ISOFormatError(
            'Interval delimiter "{0}" is not in interval '
            'string "{1}".'.format(intervaldelimiter, isointervalstr)
        )

    # Parse the number of iterations
    iterationpart, intervalpart = isointervalstr.split(intervaldelimiter, 1)

    if len(iterationpart) > 1:
        R = False
        Rnn = iterationpart[1:]
    else:
        R = True
        Rnn = None

    interval = _parse_interval(
        intervalpart, TupleBuilder, intervaldelimiter, datetimedelimiter
    )

    return builder.build_repeating_interval(R=R, Rnn=Rnn, interval=interval)


def _parse_interval(
    isointervalstr, builder, intervaldelimiter="/", datetimedelimiter="T"
):
    # Returns a tuple containing the start of the interval, the end of the
    # interval, and or the interval duration

    firstpart, secondpart = isointervalstr.split(intervaldelimiter)

    if len(firstpart) == 0 or len(secondpart) == 0:
        raise ISOFormatError(
            "{0} is not a valid ISO 8601 interval".format(isointervalstr)
        )

    if firstpart[0] == "P":
        # <duration>/<end>
        # Notice that these are not returned 'in order' (earlier to later), this
        # is to maintain consistency with parsing <start>/<end> durations, as
        # well as making repeating interval code cleaner. Users who desire
        # durations to be in order can use the 'sorted' operator.
        duration = parse_duration(firstpart, builder=TupleBuilder)

        # We need to figure out if <end> is a date, or a datetime
        if secondpart.find(datetimedelimiter) != -1:
            # <end> is a datetime
            endtuple = parse_datetime(
                secondpart, delimiter=datetimedelimiter, builder=TupleBuilder
            )
        else:
            endtuple = parse_date(secondpart, builder=TupleBuilder)

        return builder.build_interval(end=endtuple, duration=duration)
    elif secondpart[0] == "P":
        # <start>/<duration>
        # We need to figure out if <start> is a date, or a datetime
        duration = parse_duration(secondpart, builder=TupleBuilder)

        if firstpart.find(datetimedelimiter) != -1:
            # <start> is a datetime
            starttuple = parse_datetime(
                firstpart, delimiter=datetimedelimiter, builder=TupleBuilder
            )
        else:
            # <start> must just be a date
            starttuple = parse_date(firstpart, builder=TupleBuilder)

        return builder.build_interval(start=starttuple, duration=duration)

    # <start>/<end>
    if firstpart.find(datetimedelimiter) != -1:
        # Both parts are datetimes
        starttuple = parse_datetime(
            firstpart, delimiter=datetimedelimiter, builder=TupleBuilder
        )
    else:
        starttuple = parse_date(firstpart, builder=TupleBuilder)

    endtuple = _parse_interval_end(secondpart, starttuple, datetimedelimiter)

    return builder.build_interval(start=starttuple, end=endtuple)


def _parse_interval_end(endstr, starttuple, datetimedelimiter):
    datestr = None
    timestr = None

    monthstr = None
    daystr = None

    concise = False

    if type(starttuple) is DateTuple:
        startdatetuple = starttuple
    else:
        # Start is a datetime
        startdatetuple = starttuple.date

    if datetimedelimiter in endstr:
        datestr, timestr = endstr.split(datetimedelimiter, 1)
    elif ":" in endstr:
        timestr = endstr
    else:
        datestr = endstr

    if timestr is not None:
        endtimetuple = parse_time(timestr, builder=TupleBuilder)

    # End is just a time
    if datestr is None:
        return endtimetuple

    # Handle backwards concise representation
    if datestr.count("-") == 1:
        monthstr, daystr = datestr.split("-")
        concise = True
    elif len(datestr) <= 2:
        daystr = datestr
        concise = True
    elif len(datestr) <= 4:
        monthstr = datestr[0:2]
        daystr = datestr[2:]
        concise = True

    if concise is True:
        concisedatestr = startdatetuple.YYYY

        # Separators required because concise elements may be missing digits
        if monthstr is not None:
            concisedatestr += "-" + monthstr
        elif startdatetuple.MM is not None:
            concisedatestr += "-" + startdatetuple.MM

        concisedatestr += "-" + daystr

        enddatetuple = parse_date(concisedatestr, builder=TupleBuilder)

        # Clear unsupplied components
        if monthstr is None:
            enddatetuple = TupleBuilder.build_date(DD=enddatetuple.DD)
        else:
            # Year not provided
            enddatetuple = TupleBuilder.build_date(
                MM=enddatetuple.MM, DD=enddatetuple.DD
            )
    else:
        enddatetuple = parse_date(datestr, builder=TupleBuilder)

    if timestr is None:
        return enddatetuple

    return TupleBuilder.build_datetime(enddatetuple, endtimetuple)