Skip to content

Value Converters

convert_to_bool_string

Turns a value into a bool string, suitable for an XML. It is case-insensitive, meaning that the words can also be capitalised.

Accepted values
  • false, 0, 0.0, no, non, nein -> False
  • true, 1, 1.0, yes, oui, ja, sì -> True

Parameters:

Name Type Description Default
value Any

value to transform

required

Returns:

Type Description
bool

True or False if it is an accepted value.

Examples:

result = xmllib.convert_to_bool_string(1)
# result == True
result = xmllib.convert_to_bool_string("nein")
# result == False
result = xmllib.convert_to_bool_string(None)
# raises XmllibInputError
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
def convert_to_bool_string(value: Any) -> bool:
    """
    Turns a value into a bool string, suitable for an XML.
    It is case-insensitive, meaning that the words can also be capitalised.

    Accepted values:
         - `false`, `0`, `0.0`, `no`, `non`, `nein` -> `False`
         - `true`, `1`, `1.0`, `yes`, `oui`, `ja`, `sì` -> `True`

    Args:
        value: value to transform

    Returns:
        `True` or `False` if it is an accepted value.

    Raises:
        XmllibInputError: If the value is not convertable to a boolean

    Examples:
        ```python
        result = xmllib.convert_to_bool_string(1)
        # result == True
        ```

        ```python
        result = xmllib.convert_to_bool_string("nein")
        # result == False
        ```

        ```python
        result = xmllib.convert_to_bool_string(None)
        # raises XmllibInputError
        ```
    """
    str_val = str(value).lower().strip()
    if str_val in ("false", "0", "0.0", "no", "non", "nein"):
        return False
    elif str_val in ("true", "1", "1.0", "yes", "oui", "ja", "sì"):
        return True
    raise_xmllib_input_error(MessageInfo(f"The entered value '{value}' cannot be converted to a bool."))

dms_to_decimal_degrees

Convert a coordinate given in degrees, minutes and seconds to decimal degrees, which is the form a geolocation takes in CRS84.

The result is signed by the direction: north and east are positive, south and west are negative. It has four more decimal places than the seconds, so that converting it back gives the seconds at the precision they were given in.

Parameters:

Name Type Description Default
degrees int | str

the whole degrees, 0 to 90 for north/south, 0 to 180 for east/west

required
minutes int | str

the whole minutes, 0 to 59

required
seconds float | int | str

the seconds, at least 0 and less than 60

required
direction str

N, S, E or W

required

Returns:

Type Description
str

The coordinate in decimal degrees, as a string

Examples:

result = xmllib.dms_to_decimal_degrees(47, 22, 13.2, "N")
# result == "47.37033"
result = xmllib.dms_to_decimal_degrees(8, 32, 24, "E")
# result == "8.5400"
result = xmllib.dms_to_decimal_degrees("33", "52", "4.36", "S")
# result == "-33.867878"
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
 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
def dms_to_decimal_degrees(degrees: int | str, minutes: int | str, seconds: float | int | str, direction: str) -> str:
    """
    Convert a coordinate given in degrees, minutes and seconds to decimal degrees,
    which is the form a geolocation takes in `CRS84`.

    The result is signed by the direction: north and east are positive, south and west are negative.
    It has four more decimal places than the seconds,
    so that converting it back gives the seconds at the precision they were given in.

    Args:
        degrees: the whole degrees, 0 to 90 for north/south, 0 to 180 for east/west
        minutes: the whole minutes, 0 to 59
        seconds: the seconds, at least 0 and less than 60
        direction: `N`, `S`, `E` or `W`

    Returns:
        The coordinate in decimal degrees, as a string

    Raises:
        XmllibInputError: if a part is not a number, is out of range, or the direction is unknown

    Examples:
        ```python
        result = xmllib.dms_to_decimal_degrees(47, 22, 13.2, "N")
        # result == "47.37033"
        ```

        ```python
        result = xmllib.dms_to_decimal_degrees(8, 32, 24, "E")
        # result == "8.5400"
        ```

        ```python
        result = xmllib.dms_to_decimal_degrees("33", "52", "4.36", "S")
        # result == "-33.867878"
        ```
    """
    input_str = f"{degrees}° {minutes}' {seconds}\" {direction}"
    maximum_by_direction = {"N": 90, "S": 90, "E": 180, "W": 180}
    direction_upper = str(direction).strip().upper()
    if direction_upper not in maximum_by_direction:
        _raise_dms_error(input_str, "The direction must be one of N, S, E or W.")
    deg_str, min_str = str(degrees).strip(), str(minutes).strip()
    sec_str = ordinate_to_str(seconds)
    if not regex.fullmatch(r"[0-9]+", deg_str) or not regex.fullmatch(r"[0-9]+", min_str):
        _raise_dms_error(input_str, "The degrees and minutes must be whole numbers.")
    if not regex.fullmatch(r"[0-9]+(\.[0-9]+)?", sec_str):
        _raise_dms_error(input_str, "The seconds must be a decimal number.")
    # Enough precision for the quantization below, however many decimals the seconds have.
    with localcontext() as ctx:
        ctx.prec = len(deg_str) + len(sec_str) + 10
        deg, mins, secs = Decimal(deg_str), Decimal(min_str), Decimal(sec_str)
        if mins >= 60 or secs >= 60:
            _raise_dms_error(input_str, "The minutes and seconds must be less than 60.")
        value = deg + mins / 60 + secs / 3600
        if value > maximum_by_direction[direction_upper]:
            _raise_dms_error(
                input_str,
                f"A coordinate towards {direction_upper} must not exceed {maximum_by_direction[direction_upper]}°.",
            )
        seconds_places = len(sec_str.partition(".")[2])
        rounded = value.quantize(Decimal(1).scaleb(-(seconds_places + 4)))
        if direction_upper in ("S", "W") and rounded != 0:
            rounded = -rounded
    return format(rounded, "f")

crs84_to_lv95

Convert coordinates from CRS84 (WGS84) to the Swiss coordinate system LV95.

The conversion uses the approximate formulas of swisstopo. They are accurate to about 1 metre, and they apply to Switzerland only. add_geolocation() warns if a result is outside the range of LV95.

Parameters:

Name Type Description Default
value GeographicCRS84

the coordinates in CRS84

required

Returns:

Type Description
ProjectedLV95

The coordinates in LV95, rounded to 2 decimal places

Examples:

result = xmllib.crs84_to_lv95(
    xmllib.GeographicCRS84.create_new(longitude="8.730497222", latitude="46.044130556")
)
# result == xmllib.ProjectedLV95.create_new(easting="2699999.76", northing="1099999.97")
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
def crs84_to_lv95(value: GeographicCRS84) -> ProjectedLV95:
    """
    Convert coordinates from `CRS84` (WGS84) to the Swiss coordinate system `LV95`.

    The conversion uses the approximate formulas of swisstopo.
    They are accurate to about 1 metre, and they apply to Switzerland only.
    `add_geolocation()` warns if a result is outside the range of `LV95`.

    Args:
        value: the coordinates in `CRS84`

    Returns:
        The coordinates in `LV95`, rounded to 2 decimal places

    Raises:
        XmllibInputError: if the value is not `xmllib.GeographicCRS84`, or a coordinate is not a decimal number

    Examples:
        ```python
        result = xmllib.crs84_to_lv95(
            xmllib.GeographicCRS84.create_new(longitude="8.730497222", latitude="46.044130556")
        )
        # result == xmllib.ProjectedLV95.create_new(easting="2699999.76", northing="1099999.97")
        ```
    """
    check_raise_if_not_geolocation_coordinates(value, GeographicCRS84)
    longitude, latitude = _get_coordinate_as_float(value.longitude), _get_coordinate_as_float(value.latitude)
    # Auxiliary values of the swisstopo formulas: the distance to the old Bern observatory, in units of 10000"
    phi = (latitude * 3600 - 169028.66) / 10000
    lam = (longitude * 3600 - 26782.5) / 10000
    easting = 2600072.37 + 211455.93 * lam - 10938.51 * lam * phi - 0.36 * lam * phi**2 - 44.54 * lam**3
    northing = (
        1200147.07 + 308807.95 * phi + 3745.25 * lam**2 + 76.63 * phi**2 - 194.56 * lam**2 * phi + 119.79 * phi**3
    )
    return ProjectedLV95.create_new(easting=f"{easting:.2f}", northing=f"{northing:.2f}")

lv95_to_crs84

Convert coordinates from the Swiss coordinate system LV95 to CRS84 (WGS84).

The conversion uses the approximate formulas of swisstopo. They are accurate to about 1 metre, and they apply to Switzerland only.

Parameters:

Name Type Description Default
value ProjectedLV95

the coordinates in LV95

required

Returns:

Type Description
GeographicCRS84

The coordinates in CRS84, rounded to 6 decimal places

Examples:

result = xmllib.lv95_to_crs84(xmllib.ProjectedLV95.create_new(easting="2700000", northing="1100000"))
# result == xmllib.GeographicCRS84.create_new(longitude="8.730499", latitude="46.044127")
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
def lv95_to_crs84(value: ProjectedLV95) -> GeographicCRS84:
    """
    Convert coordinates from the Swiss coordinate system `LV95` to `CRS84` (WGS84).

    The conversion uses the approximate formulas of swisstopo.
    They are accurate to about 1 metre, and they apply to Switzerland only.

    Args:
        value: the coordinates in `LV95`

    Returns:
        The coordinates in `CRS84`, rounded to 6 decimal places

    Raises:
        XmllibInputError: if the value is not `xmllib.ProjectedLV95`, or a coordinate is not a decimal number

    Examples:
        ```python
        result = xmllib.lv95_to_crs84(xmllib.ProjectedLV95.create_new(easting="2700000", northing="1100000"))
        # result == xmllib.GeographicCRS84.create_new(longitude="8.730499", latitude="46.044127")
        ```
    """
    check_raise_if_not_geolocation_coordinates(value, ProjectedLV95)
    easting, northing = _get_coordinate_as_float(value.easting), _get_coordinate_as_float(value.northing)
    # Auxiliary values of the swisstopo formulas: the distance to the projection centre, in units of 1000 km
    y = (easting - 2600000) / 1000000
    x = (northing - 1200000) / 1000000
    lam = 2.6779094 + 4.728982 * y + 0.791484 * y * x + 0.1306 * y * x**2 - 0.0436 * y**3
    phi = 16.9023892 + 3.238272 * x - 0.270978 * y**2 - 0.002528 * x**2 - 0.0447 * y**2 * x - 0.0140 * x**3
    # lam and phi are in units of 10000"
    return GeographicCRS84.create_new(longitude=f"{lam * 100 / 36:.6f}", latitude=f"{phi * 100 / 36:.6f}")

replace_newlines_with_tags

Converts the newlines in a string to XML tags.

Parameters:

Name Type Description Default
text str

string to convert

required
converter_option NewlineReplacement

specifies what tag to use instead of the newline

required

Returns:

Type Description
str

String with replaced values

Examples:

result = xmllib.replace_newlines_with_tags(
    "Start\nEnd", xmllib.NewlineReplacement.NONE
)
# result == "Start\nEnd"
result = xmllib.replace_newlines_with_tags(
    "Start\nEnd", xmllib.NewlineReplacement.LINEBREAK
)
# result == "Start<br/>End"
result = xmllib.replace_newlines_with_tags(
    "Start\n\nEnd", xmllib.NewlineReplacement.PARAGRAPH
)
# result == "<p>Start</p><p>End</p>"
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
def replace_newlines_with_tags(text: str, converter_option: NewlineReplacement) -> str:
    """
    Converts the newlines in a string to XML tags.

    Args:
        text: string to convert
        converter_option: specifies what tag to use instead of the newline

    Returns:
        String with replaced values

    Raises:
        XmllibInputError: If an invalid conversion option is given

    Examples:
        ```python
        result = xmllib.replace_newlines_with_tags(
            "Start\\nEnd", xmllib.NewlineReplacement.NONE
        )
        # result == "Start\\nEnd"
        ```

        ```python
        result = xmllib.replace_newlines_with_tags(
            "Start\\nEnd", xmllib.NewlineReplacement.LINEBREAK
        )
        # result == "Start<br/>End"
        ```

        ```python
        result = xmllib.replace_newlines_with_tags(
            "Start\\n\\nEnd", xmllib.NewlineReplacement.PARAGRAPH
        )
        # result == "<p>Start</p><p>End</p>"
        ```
    """
    match converter_option:
        case NewlineReplacement.NONE:
            return text
        case NewlineReplacement.LINEBREAK:
            return replace_newlines_with_br_tags(text)
        case NewlineReplacement.PARAGRAPH:
            return replace_newlines_with_paragraph_tags(text)

replace_newlines_with_paragraph_tags

Replace Start\nEnd with <p>Start</p><p>End</p>

Parameters:

Name Type Description Default
text str

string to be formatted

required

Returns:

Type Description
str

Formatted string with paragraph tags

Examples:

result = xmllib.replace_newlines_with_paragraph_tags("Start\nEnd")
# result == "<p>Start</p><p>End</p>"
# multiple consecutive newlines will be treated as one newline

result = xmllib.replace_newlines_with_paragraph_tags("Start\n\nEnd")
# result == "<p>Start</p><p>End</p>"
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
def replace_newlines_with_paragraph_tags(text: str) -> str:
    """
    Replace `Start\\nEnd` with `<p>Start</p><p>End</p>`

    Args:
        text: string to be formatted

    Returns:
        Formatted string with paragraph tags

    Examples:
        ```python
        result = xmllib.replace_newlines_with_paragraph_tags("Start\\nEnd")
        # result == "<p>Start</p><p>End</p>"
        ```

        ```python
        # multiple consecutive newlines will be treated as one newline

        result = xmllib.replace_newlines_with_paragraph_tags("Start\\n\\nEnd")
        # result == "<p>Start</p><p>End</p>"
        ```
    """
    splt = [x for x in text.split("\n") if x != ""]
    formatted = [f"<p>{x}</p>" for x in splt]
    return "".join(formatted)

replace_newlines_with_br_tags

Replaces \n with <br/>

Parameters:

Name Type Description Default
text str

string to be formatted

required

Returns:

Type Description
str

Formatted string with break-line tags

Examples:

result = xmllib.replace_newlines_with_br_tags("Start\nEnd")
# result == "Start<br/>End"
# multiple consecutive newlines will be converted into multiple break-lines

result = xmllib.replace_newlines_with_br_tags("Start\n\nEnd")
# result == "Start<br/><br/>End"
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def replace_newlines_with_br_tags(text: str) -> str:
    """
    Replaces `\\n` with `<br/>`

    Args:
        text: string to be formatted

    Returns:
        Formatted string with break-line tags

    Examples:
        ```python
        result = xmllib.replace_newlines_with_br_tags("Start\\nEnd")
        # result == "Start<br/>End"
        ```

        ```python
        # multiple consecutive newlines will be converted into multiple break-lines

        result = xmllib.replace_newlines_with_br_tags("Start\\n\\nEnd")
        # result == "Start<br/><br/>End"
        ```
    """
    return text.replace("\n", "<br/>")

reformat_date

Reformats a date string into the DSP format.

  • If the input cannot be reformatted according to the configuration, or if the result is not a valid DSP date, a warning is emitted and the original input is returned.
  • If the input is empty, a warning is emitted and an empty string is returned.
  • If the input is already a correctly formatted DSP-date, the original input is returned.

Parameters:

Name Type Description Default
date str | int

date string to be reformatted

required
date_precision_separator str | None

the separation between the day, month and year

required
date_range_separator str | None

the separation between two dates

required
date_format DateFormat

the format of the date, see DateFormat for options

required
calendar Calendar

the calendar of the date, see Calendar for options

GREGORIAN
era Era | None

the era of the date, see Era for options

CE
resource_id str | None

the ID of the associated resource, this is to improve the error message

None

Returns:

Type Description
str

A reformatted date or the original input if the reformatted result is not a valid DSP date

Examples:

# default configuration, starting with the day
result = xmllib.reformat_date(
    date="1.11.2000",
    date_precision_separator=".",
    date_range_separator=None,
    date_format=xmllib.DateFormat.DD_MM_YYYY
)
# result == "GREGORIAN:CE:2000-11-1:CE:2000-11-1"
# default configuration, but starting with the year
result = xmllib.reformat_date(
    date="2000.11.1",
    date_precision_separator=".",
    date_range_separator=None,
    date_format=xmllib.DateFormat.YYYY_MM_DD,
)
# result == "GREGORIAN:CE:2000-11-1:CE:2000-11-1"
# with a date range
result = xmllib.reformat_date(
    date="1.11.2000-2001",
    date_precision_separator=".",
    date_range_separator="-",
    date_format=xmllib.DateFormat.DD_MM_YYYY,
)
# result == "GREGORIAN:CE:2000-11-1:CE:2001"
# islamic calendar, where eras are not allowed
result = xmllib.reformat_date(
    date="1.11.2000",
    date_precision_separator=".",
    date_range_separator=None,
    date_format=xmllib.DateFormat.DD_MM_YYYY,
    calendar=xmllib.Calendar.ISLAMIC,
    era=None
)
# result == "ISLAMIC:2000-11-1:2000-11-1"
# with a different era
result = xmllib.reformat_date(
    date="1.11.2000",
    date_precision_separator=".",
    date_range_separator="-",
    date_format=xmllib.DateFormat.DD_MM_YYYY,
    era=xmllib.Era.AD
)
# result == "GREGORIAN:AD:2000-11-1:AD:2000-11-1"
# reformatted date, no precision in the date string is required
result = xmllib.reformat_date(
    date="2000",
    date_precision_separator=".",
    date_range_separator="-",
    date_format=xmllib.DateFormat.DD_MM_YYYY,
)
# result == "GREGORIAN:CE:2000:CE:2000"
# already correctly formatted date
result = xmllib.reformat_date(
    date="GREGORIAN:CE:2000:CE:2000",
    date_precision_separator=".",
    date_range_separator="-",
    date_format=xmllib.DateFormat.DD_MM_YYYY,
)
# result == "GREGORIAN:CE:2000:CE:2000"
# invalid input: a warning is emitted and the original input is returned
result = xmllib.reformat_date(
    date="not-a-date",
    date_precision_separator=".",
    date_range_separator="-",
    date_format=xmllib.DateFormat.DD_MM_YYYY,
)
# WARNING is emitted
# result == "not-a-date"
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def reformat_date(
    date: str | int,
    date_precision_separator: str | None,
    date_range_separator: str | None,
    date_format: DateFormat,
    calendar: Calendar = Calendar.GREGORIAN,
    era: Era | None = Era.CE,
    resource_id: str | None = None,
) -> str:
    """
    Reformats a date string into the DSP format.

    - If the input cannot be reformatted according to the configuration, or if the result
      is not a valid DSP date, a warning is emitted and the original input is returned.
    - If the input is empty, a warning is emitted and an empty string is returned.
    - If the input is already a correctly formatted DSP-date, the original input is returned.

    Args:
        date: date string to be reformatted
        date_precision_separator: the separation between the day, month and year
        date_range_separator: the separation between two dates
        date_format: the format of the date, see [`DateFormat` for options](https://docs.dasch.swiss/DSP-TOOLS/xmllib-docs/date_formats/#xmllib.models.date_formats.DateFormat)
        calendar: the calendar of the date, see [`Calendar` for options](https://docs.dasch.swiss/DSP-TOOLS/xmllib-docs/date_formats/#xmllib.models.date_formats.Calendar)
        era: the era of the date, see [`Era` for options](https://docs.dasch.swiss/DSP-TOOLS/xmllib-docs/date_formats/#xmllib.models.date_formats.Era)
        resource_id: the ID of the associated resource, this is to improve the error message

    Returns:
        A reformatted date or the original input if the reformatted result is not a valid DSP date

    Examples:
        ```python
        # default configuration, starting with the day
        result = xmllib.reformat_date(
            date="1.11.2000",
            date_precision_separator=".",
            date_range_separator=None,
            date_format=xmllib.DateFormat.DD_MM_YYYY
        )
        # result == "GREGORIAN:CE:2000-11-1:CE:2000-11-1"
        ```

        ```python
        # default configuration, but starting with the year
        result = xmllib.reformat_date(
            date="2000.11.1",
            date_precision_separator=".",
            date_range_separator=None,
            date_format=xmllib.DateFormat.YYYY_MM_DD,
        )
        # result == "GREGORIAN:CE:2000-11-1:CE:2000-11-1"
        ```

        ```python
        # with a date range
        result = xmllib.reformat_date(
            date="1.11.2000-2001",
            date_precision_separator=".",
            date_range_separator="-",
            date_format=xmllib.DateFormat.DD_MM_YYYY,
        )
        # result == "GREGORIAN:CE:2000-11-1:CE:2001"
        ```

        ```python
        # islamic calendar, where eras are not allowed
        result = xmllib.reformat_date(
            date="1.11.2000",
            date_precision_separator=".",
            date_range_separator=None,
            date_format=xmllib.DateFormat.DD_MM_YYYY,
            calendar=xmllib.Calendar.ISLAMIC,
            era=None
        )
        # result == "ISLAMIC:2000-11-1:2000-11-1"
        ```

        ```python
        # with a different era
        result = xmllib.reformat_date(
            date="1.11.2000",
            date_precision_separator=".",
            date_range_separator="-",
            date_format=xmllib.DateFormat.DD_MM_YYYY,
            era=xmllib.Era.AD
        )
        # result == "GREGORIAN:AD:2000-11-1:AD:2000-11-1"
        ```

        ```python
        # reformatted date, no precision in the date string is required
        result = xmllib.reformat_date(
            date="2000",
            date_precision_separator=".",
            date_range_separator="-",
            date_format=xmllib.DateFormat.DD_MM_YYYY,
        )
        # result == "GREGORIAN:CE:2000:CE:2000"
        ```

        ```python
        # already correctly formatted date
        result = xmllib.reformat_date(
            date="GREGORIAN:CE:2000:CE:2000",
            date_precision_separator=".",
            date_range_separator="-",
            date_format=xmllib.DateFormat.DD_MM_YYYY,
        )
        # result == "GREGORIAN:CE:2000:CE:2000"
        ```

        ```python
        # invalid input: a warning is emitted and the original input is returned
        result = xmllib.reformat_date(
            date="not-a-date",
            date_precision_separator=".",
            date_range_separator="-",
            date_format=xmllib.DateFormat.DD_MM_YYYY,
        )
        # WARNING is emitted
        # result == "not-a-date"
        ```
    """
    if not is_nonempty_value_internal(date):
        msg_info = MessageInfo(
            "The date to be reformatted is empty. An empty string is returned.", resource_id=resource_id
        )
        emit_xmllib_input_warning(msg_info)
        return ""
    date = str(date).strip()
    invalid_date_info = MessageInfo(
        f"The provided date '{date}' does not conform to the expected format, the original value is returned.",
        resource_id=resource_id,
    )
    # Here we want to check if the input is already a reformatted date. In that case, we would expect a calendar.
    # The function that checks if an input is a valid date does not require a calendar,
    # so unformatted input for example, '2000' may be accepted as a valid date.
    if regex.search(r"(GREGORIAN|JULIAN|ISLAMIC)", date):
        if is_date_internal(date):
            return date
        else:
            emit_xmllib_input_warning(invalid_date_info)
            return date
    if date_precision_separator and date_range_separator:
        if date_precision_separator == date_range_separator:
            msg_info = MessageInfo(
                f"The precision separator and range separator provided are identical: '{date_precision_separator}'. "
                f"This is not allowed.",
                resource_id=resource_id,
            )
            raise_xmllib_input_error(msg_info)
    if date_range_separator is not None:
        date_split = [found for x in date.split(date_range_separator) if (found := x.strip())]
    else:
        date_split = [date.strip()]
    all_dates = [_reformat_single_date(x, date_precision_separator, date_format, resource_id) for x in date_split]
    if era:
        all_dates = [f"{era.value}:{x}" for x in all_dates]
    if len(all_dates) == 1:
        all_dates.append(all_dates[0])
    reformatted_str = ":".join(all_dates)
    if calendar:
        reformatted_str = f"{calendar.value}:{reformatted_str}"
    if is_date_internal(reformatted_str):
        return reformatted_str
    emit_xmllib_input_warning(invalid_date_info)
    return date

find_dates_in_string

Checks if a string contains date values (single dates, or date ranges), and return all found dates as set of DSP-formatted strings. Returns an empty set if no date was found. See XML documentation for details.

Notes
  • If no era or calendar is given, dates are interpreted in the Common Era and the Gregorian calendar.
  • Standalone numbers from 000-2999, in 3/4-digit form, are interpreted as years CE.
  • If a number (with any number of digits) is followed by CE, C.E., AD, A.D., it is interpreted as years CE.
  • If a number (with any number of digits) is followed by BCE, BC, B.C., B.C.E., av. J.-C., it is interpreted as years BCE.
  • Dates written with slashes are always interpreted in a European manner: 5/11/2021 is the 5th of November.
  • In the European notation, 2-digit years are expanded to 4 digits, with the current year as watershed:
    • 30.4.24 -> 30.04.2024
    • 30.4.50 -> 30.04.1950
Currently supported date formats
  • 0476-09-04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
  • 0476_09_04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
  • 30.4.2021 -> GREGORIAN:CE:2021-04-30:CE:2021-04-30
  • 30.4.21 -> GREGORIAN:CE:2021-04-30:CE:2021-04-30
  • 5/11/2021 -> GREGORIAN:CE:2021-11-05:CE:2021-11-05
  • Jan 26, 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
  • 26 Jan 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
  • 26 January 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
    1. Jan. 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
    1. Januar 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
  • 28.2.-1.12.1515 -> GREGORIAN:CE:1515-02-28:CE:1515-12-01
  • 25.-26.2.0800 -> GREGORIAN:CE:0800-02-25:CE:0800-02-26
  • 1.9.2022-3.1.2024 -> GREGORIAN:CE:2022-09-01:CE:2024-01-03
  • 1848 -> GREGORIAN:CE:1848:CE:1848
  • 1849/1850 -> GREGORIAN:CE:1849:CE:1850
  • 1849/50 -> GREGORIAN:CE:1849:CE:1850
  • 1845-50 -> GREGORIAN:CE:1845:CE:1850
  • 840-50 -> GREGORIAN:CE:840:CE:850
  • 840-1 -> GREGORIAN:CE:840:CE:841
  • 9 BC / 9 B.C. / 9 B.C.E. / 9 BCE -> GREGORIAN:BC:9:BC:9
  • 20 BCE - 50 CE -> GREGORIAN:BC:20:CE:50
  • 1000-900 av. J.-C. -> GREGORIAN:BC:1000:BC:900
  • 45 av. J.-C. -> GREGORIAN:BC:45:BC:45

Parameters:

Name Type Description Default
string str

string to check

required

Returns:

Type Description
set[str]

(possibly empty) set of DSP-formatted date strings

Examples:

result = xmllib.find_dates_in_string("1849/1850")
# result == {"GREGORIAN:CE:1849:CE:1850"}
result = xmllib.find_dates_in_string("not a valid date")
# result == {}
result = xmllib.find_dates_in_string("first date: 2024. Second: 2025.")
# result == {"GREGORIAN:CE:2024:CE:2024", "GREGORIAN:CE:2025:CE:2025"}
Source code in dsp/dsp-tools/src/dsp_tools/xmllib/value_converters.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def find_dates_in_string(string: str) -> set[str]:
    """
    Checks if a string contains date values (single dates, or date ranges),
    and return all found dates as set of DSP-formatted strings.
    Returns an empty set if no date was found.
    [See XML documentation for details](https://docs.dasch.swiss/DSP-TOOLS/data-file/xml-data-file/#date).

    Notes:
        - If no era or calendar is given, dates are interpreted in the Common Era and the Gregorian calendar.
        - Standalone numbers from 000-2999, in 3/4-digit form, are interpreted as years CE.
        - If a number (with any number of digits) is followed by CE, C.E., AD, A.D., it is interpreted as years CE.
        - If a number (with any number of digits) is followed by BCE, BC, B.C., B.C.E., av. J.-C.,
          it is interpreted as years BCE.
        - Dates written with slashes are always interpreted in a European manner: 5/11/2021 is the 5th of November.
        - In the European notation, 2-digit years are expanded to 4 digits, with the current year as watershed:
            - 30.4.24 -> 30.04.2024
            - 30.4.50 -> 30.04.1950

    Currently supported date formats:
        - 0476-09-04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
        - 0476_09_04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
        - 30.4.2021 -> GREGORIAN:CE:2021-04-30:CE:2021-04-30
        - 30.4.21 -> GREGORIAN:CE:2021-04-30:CE:2021-04-30
        - 5/11/2021 -> GREGORIAN:CE:2021-11-05:CE:2021-11-05
        - Jan 26, 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
        - 26 Jan 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
        - 26 January 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
        - 26. Jan. 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
        - 26. Januar 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
        - 28.2.-1.12.1515 -> GREGORIAN:CE:1515-02-28:CE:1515-12-01
        - 25.-26.2.0800 -> GREGORIAN:CE:0800-02-25:CE:0800-02-26
        - 1.9.2022-3.1.2024 -> GREGORIAN:CE:2022-09-01:CE:2024-01-03
        - 1848 -> GREGORIAN:CE:1848:CE:1848
        - 1849/1850 -> GREGORIAN:CE:1849:CE:1850
        - 1849/50 -> GREGORIAN:CE:1849:CE:1850
        - 1845-50 -> GREGORIAN:CE:1845:CE:1850
        - 840-50 -> GREGORIAN:CE:840:CE:850
        - 840-1 -> GREGORIAN:CE:840:CE:841
        - 9 BC / 9 B.C. / 9 B.C.E. / 9 BCE -> GREGORIAN:BC:9:BC:9
        - 20 BCE - 50 CE -> GREGORIAN:BC:20:CE:50
        - 1000-900 av. J.-C. -> GREGORIAN:BC:1000:BC:900
        - 45 av. J.-C. -> GREGORIAN:BC:45:BC:45

    Args:
        string: string to check

    Returns:
        (possibly empty) set of DSP-formatted date strings

    Examples:
        ```python
        result = xmllib.find_dates_in_string("1849/1850")
        # result == {"GREGORIAN:CE:1849:CE:1850"}
        ```

        ```python
        result = xmllib.find_dates_in_string("not a valid date")
        # result == {}
        ```

        ```python
        result = xmllib.find_dates_in_string("first date: 2024. Second: 2025.")
        # result == {"GREGORIAN:CE:2024:CE:2024", "GREGORIAN:CE:2025:CE:2025"}
        ```
    """

    # sanitise input, just in case that the function was called on an empty or N/A cell
    if not is_nonempty_value_internal(string):
        return set()
    return _find_dates_in_string(string)