isoduration.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """
  2. This module provides an ISO 8601:2004 duration parser.
  3. It also provides a wrapper to strftime. This wrapper makes it easier to
  4. format timedelta or Duration instances as ISO conforming strings.
  5. """
  6. import re
  7. from datetime import timedelta
  8. from decimal import Decimal
  9. from isodate.duration import Duration
  10. from isodate.isodatetime import parse_datetime
  11. from isodate.isoerror import ISO8601Error
  12. from isodate.isostrf import D_DEFAULT, strftime
  13. ISO8601_PERIOD_REGEX = re.compile(
  14. r"^(?P<sign>[+-])?"
  15. r"P(?!\b)"
  16. r"(?P<years>[0-9]+([,.][0-9]+)?Y)?"
  17. r"(?P<months>[0-9]+([,.][0-9]+)?M)?"
  18. r"(?P<weeks>[0-9]+([,.][0-9]+)?W)?"
  19. r"(?P<days>[0-9]+([,.][0-9]+)?D)?"
  20. r"((?P<separator>T)(?P<hours>[0-9]+([,.][0-9]+)?H)?"
  21. r"(?P<minutes>[0-9]+([,.][0-9]+)?M)?"
  22. r"(?P<seconds>[0-9]+([,.][0-9]+)?S)?)?$"
  23. )
  24. # regular expression to parse ISO duration strings.
  25. def parse_duration(datestring, as_timedelta_if_possible=True):
  26. """
  27. Parses an ISO 8601 durations into datetime.timedelta or Duration objects.
  28. If the ISO date string does not contain years or months, a timedelta
  29. instance is returned, else a Duration instance is returned.
  30. The following duration formats are supported:
  31. -PnnW duration in weeks
  32. -PnnYnnMnnDTnnHnnMnnS complete duration specification
  33. -PYYYYMMDDThhmmss basic alternative complete date format
  34. -PYYYY-MM-DDThh:mm:ss extended alternative complete date format
  35. -PYYYYDDDThhmmss basic alternative ordinal date format
  36. -PYYYY-DDDThh:mm:ss extended alternative ordinal date format
  37. The '-' is optional.
  38. Limitations: ISO standard defines some restrictions about where to use
  39. fractional numbers and which component and format combinations are
  40. allowed. This parser implementation ignores all those restrictions and
  41. returns something when it is able to find all necessary components.
  42. In detail:
  43. it does not check, whether only the last component has fractions.
  44. it allows weeks specified with all other combinations
  45. The alternative format does not support durations with years, months or
  46. days set to 0.
  47. """
  48. if not isinstance(datestring, str):
  49. raise TypeError("Expecting a string %r" % datestring)
  50. match = ISO8601_PERIOD_REGEX.match(datestring)
  51. if not match:
  52. # try alternative format:
  53. if datestring.startswith("P"):
  54. durdt = parse_datetime(datestring[1:])
  55. if as_timedelta_if_possible and durdt.year == 0 and durdt.month == 0:
  56. # FIXME: currently not possible in alternative format
  57. # create timedelta
  58. ret = timedelta(
  59. days=durdt.day,
  60. seconds=durdt.second,
  61. microseconds=durdt.microsecond,
  62. minutes=durdt.minute,
  63. hours=durdt.hour,
  64. )
  65. else:
  66. # create Duration
  67. ret = Duration(
  68. days=durdt.day,
  69. seconds=durdt.second,
  70. microseconds=durdt.microsecond,
  71. minutes=durdt.minute,
  72. hours=durdt.hour,
  73. months=durdt.month,
  74. years=durdt.year,
  75. )
  76. return ret
  77. raise ISO8601Error("Unable to parse duration string %r" % datestring)
  78. groups = match.groupdict()
  79. for key, val in groups.items():
  80. if key not in ("separator", "sign"):
  81. if val is None:
  82. groups[key] = "0n"
  83. # print groups[key]
  84. if key in ("years", "months"):
  85. groups[key] = Decimal(groups[key][:-1].replace(",", "."))
  86. else:
  87. # these values are passed into a timedelta object,
  88. # which works with floats.
  89. groups[key] = float(groups[key][:-1].replace(",", "."))
  90. if as_timedelta_if_possible and groups["years"] == 0 and groups["months"] == 0:
  91. ret = timedelta(
  92. days=groups["days"],
  93. hours=groups["hours"],
  94. minutes=groups["minutes"],
  95. seconds=groups["seconds"],
  96. weeks=groups["weeks"],
  97. )
  98. if groups["sign"] == "-":
  99. ret = timedelta(0) - ret
  100. else:
  101. ret = Duration(
  102. years=groups["years"],
  103. months=groups["months"],
  104. days=groups["days"],
  105. hours=groups["hours"],
  106. minutes=groups["minutes"],
  107. seconds=groups["seconds"],
  108. weeks=groups["weeks"],
  109. )
  110. if groups["sign"] == "-":
  111. ret = Duration(0) - ret
  112. return ret
  113. def duration_isoformat(tduration, format=D_DEFAULT):
  114. """
  115. Format duration strings.
  116. This method is just a wrapper around isodate.isostrf.strftime and uses
  117. P%P (D_DEFAULT) as default format.
  118. """
  119. # TODO: implement better decision for negative Durations.
  120. # should be done in Duration class in consistent way with timedelta.
  121. if (
  122. isinstance(tduration, Duration)
  123. and (
  124. tduration.years < 0
  125. or tduration.months < 0
  126. or tduration.tdelta < timedelta(0)
  127. )
  128. ) or (isinstance(tduration, timedelta) and (tduration < timedelta(0))):
  129. ret = "-"
  130. else:
  131. ret = ""
  132. ret += strftime(tduration, format)
  133. return ret