While chrono
supports parsing of date, time and time zone in ISO 8601 compliant format, I am unable to find any method in the crate to parse duration strings such as PT2M
which represents 2 minutes.

- 388,571
- 95
- 1,107
- 1,366

- 562
- 3
- 10
3 Answers
Chrono doesn't have any function to do this job.
Instead, use the parse_duration crate to solve the problem:
extern crate parse_duration;
use parse_duration::parse;
fn main() {
print!("{:?}", parse("2 minutes"));
}
Ok(120s)
Furthermore, there isn't any function that converts ISO 8601 shortcuts into a representation for the chrono or parse_duration crate.
You need to write a parser that transforms the shortcuts like PT2M
into a human readable form like 2 minutes
, if you work with the parse_duration crate.
If you want to use the chrono crate directly, you have a lot of calculation to do to put the duration into a numeric representation. I would take a look into the sources of parse
in parse_duration.
One workaround could be to calculate the duration out of two NaiveDate
s:
extern crate chrono;
use chrono::{Duration, NaiveDate};
fn main() {
let d = NaiveDate::from_ymd(2021, 8, 2);
let tm1 = d.and_hms(0, 0, 0);
let tm2 = d.and_hms(0, 2, 0);
let delta: Duration = tm2.signed_duration_since(tm1);
print!("{:?}", delta);
}
Duration { secs: 120, nanos: 0 }

- 2,572
- 13
- 14
-
1I'm surprised at this result. I wouldn't have thought that `".:++++]][][[][[2]][minutes][]:}}}}"` was a valid duration. – Shepmaster Aug 02 '21 at 14:48
-
1I guess the OP knows how [ISO 8601](https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) works. Why would he ask otherwise explicit for a function to parse this format? – Kaplan Aug 02 '21 at 15:03
-
2@Kaplan thanks for reference. Unfortunately, package has no longer updating notice. The reason I referenced chrono is that it is nearly feature complete with parsing ISO8601 duration. I would have very much liked to limit my dependencies. – praveent Aug 02 '21 at 15:49
-
I added a workaround that reduces the time-calculations, that are needed to instantiate a `Duration` directly. Nevertheless You must still write a parser which transforms the ISO 8601 eg. `PTM2` into `(0, 2, 0)` for 2 minutes. – Kaplan Aug 02 '21 at 16:37
-
1@Shepmaster The workaround is an addendum in response to the OP's [latest comment](https://stackoverflow.com/posts/comments/121278717?noredirect=1) *limit my dependencies* and not a new solution. – Kaplan Aug 02 '21 at 17:39
-
@Kaplan sure... but why are you telling me this? – Shepmaster Aug 02 '21 at 17:41
-
@Shepmaster Due to a *don't reply twice* comment, which has disappeared in the meantime. Sorry, I thought it came from you. – Kaplan Aug 02 '21 at 18:07
Chrono doesn't have any function to do this job.
You can use iso8601-duration crate instead.

- 632
- 8
- 8
There is also the iso8601
crate which can parse durations and dates in that format.

- 79,749
- 26
- 255
- 305