Skip to content

Add Duration.isoformat() #522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
strategy:
matrix:
python-version: [2.7, 3.5, 3.6, 3.7, 3.8, pypy3]
fail-fast: false

steps:
- uses: actions/checkout@v2
Expand Down Expand Up @@ -68,6 +69,7 @@ jobs:
strategy:
matrix:
python-version: [2.7, 3.5, 3.6, 3.7, 3.8, pypy3]
fail-fast: false

steps:
- uses: actions/checkout@v2
Expand Down Expand Up @@ -112,6 +114,7 @@ jobs:
strategy:
matrix:
python-version: [2.7, 3.5, 3.6, 3.7, 3.8]
fail-fast: false

steps:
- uses: actions/checkout@v2
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ setup.py
# editor

.vscode

# dev

.venv
19 changes: 19 additions & 0 deletions docs/docs/duration.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,22 @@ It also has a handy `in_words()` method, which determines the duration represent
>>> it.in_words(locale='de')
'168 Wochen 1 Tag 2 Stunden 1 Minute 24 Sekunden'
```

Finally, it has an
[ISO-8601-compliant](https://en.wikipedia.org/wiki/ISO_8601#Durations) `isformat()`
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you meant isoformat()

method for cross-platform representation.

```python

>>> import pendulum

>>> dur = pendulum.duration(years=1, months=3, days=6, seconds=3)

>>> iso = dur.isoformat()

>>> print(iso)
'P1Y3M6DT0H0M3S'

>>> pendulum.parse(iso) == dur
True
```
5 changes: 4 additions & 1 deletion pendulum/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,10 @@ def yesterday(tz="local"): # type: (Union[str, _Timezone]) -> DateTime


def from_format(
string, fmt, tz=UTC, locale=None, # noqa
string,
fmt,
tz=UTC,
locale=None, # noqa
): # type: (str, str, Union[str, _Timezone], Optional[str]) -> DateTime
"""
Creates a DateTime instance from a specific format.
Expand Down
23 changes: 23 additions & 0 deletions pendulum/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,29 @@ def __divmod__(self, other):

return NotImplemented

def isoformat(self) -> str:
"""Represent this duration as a ISO-8601-compliant string."""
periods = [
("Y", self.years),
("M", self.months),
("D", self.remaining_days),
]
Comment on lines +419 to +423

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing weeks,

Suggested change
periods = [
("Y", self.years),
("M", self.months),
("D", self.remaining_days),
]
periods = [
("Y", self.years),
("M", self.months),
("W", self.weeks),
("D", self.remaining_days),
]

period = "P"
for sym, val in periods:
period += "{val}{sym}".format(val=val, sym=sym)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you only keep the components that are set, .isoformat() becomes a proper inverse transformation of str → Duration

assert pendulum.parse("P1W").isoformat() == "P1W"

need same change below obviously

times = [
("H", self.hours),
("M", self.minutes),
("S", self.remaining_seconds),
]
time = "T"
for sym, val in times:
time += "{val}{sym}".format(val=val, sym=sym)
if self.microseconds:
time = time[:-1]
time += ".{ms:06}S".format(ms=self.microseconds)
return period + time


Duration.min = Duration(days=-999999999)
Duration.max = Duration(
Expand Down
3 changes: 2 additions & 1 deletion tests/datetime/test_from_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def test_from_format_with_timezone():
def test_from_format_with_square_bracket_in_timezone():
with pytest.raises(ValueError, match="^String does not match format"):
pendulum.from_format(
"1975-05-21 22:32:11 Eu[rope/London", "YYYY-MM-DD HH:mm:ss z",
"1975-05-21 22:32:11 Eu[rope/London",
"YYYY-MM-DD HH:mm:ss z",
)


Expand Down
32 changes: 32 additions & 0 deletions tests/duration/test_isoformat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import pytest

from pendulum import Duration
from pendulum import parse


@pytest.mark.parametrize(
"dur, expected_iso",
[
(
Duration(
years=1,
months=3,
days=6,
minutes=50,
seconds=3,
milliseconds=10,
microseconds=10,
),
"P1Y3M6DT0H50M3.010010S",
),
(Duration(days=4, hours=12, minutes=30, seconds=5), "P0Y0M4DT12H30M5S"),
(Duration(days=4, hours=12, minutes=30, seconds=5), "P0Y0M4DT12H30M5S"),
(Duration(microseconds=10), "P0Y0M0DT0H0M0.000010S"),
(Duration(milliseconds=1), "P0Y0M0DT0H0M0.001000S"),
(Duration(minutes=1), "P0Y0M0DT0H1M0S"),
],
)
def test_isoformat(dur, expected_iso):
fmt = dur.isoformat()
assert fmt == expected_iso
assert parse(fmt) == dur