Skip to content
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

Coercion of a duration into a character and back does not work #1005

tvatter opened this issue Nov 17, 2021 · 3 comments

Coercion of a duration into a character and back does not work #1005

tvatter opened this issue Nov 17, 2021 · 3 comments


Copy link

tvatter commented Nov 17, 2021


While coercing a duration into a character work, the output of the coercion into a character can't be coerced back into a duration.

(x <- duration(1, "years"))  # [1] "31557600s (~1 years)"
(y <- as.character(x))         # [1] "31557600s (~1 years)"
(z <- as.duration(y))           # [1] NA

I understand that the basic purpose of the parser is different and that this behavior is expected. However, I just encountered a situation where this is problematic:

df <- tibble(x = duration(1, "years"))     # x is a duration
tmp <- tempfile(); write_csv(df, tmp)    # write the df to file
df2 <- read_csv(tmp)                           # x is now a character which can't be easily coerced

Now, I get that one could just convert a duration as a numeric before writing, via mutate(across(where(is.duration), as.numeric)) or the "old" way mutate_if(is.duration, as.numeric). But it seems like an unnecessary burden to the user, especially since this behavior is not, to the best of my knowledge, documented.

I will also file a bug report in readr. While I understand that readr can't be expected to know whether to coerce to numeric or character for every object class out there, I would have expected that classes from the tidyverse packages should be supported seamlessly. However, it seems that the "responsibility" of providing a parser for the duration class should be on lubridate.


Copy link

tvatter commented Nov 17, 2021

Edit, I see that this isn't a new problem with readr:

Copy link

surdina commented Jan 11, 2022

I just came across the same thing!

Perhaps rather naively, it also seems to me that as.duration() should be able to handle the string format it produces. The information is still there, and the coercion could be achieved by reading the string and ignoring everything after s.

Right now, for character input, as.duration() calls as.period(), which calls parse_period(), which calls C_parse_period(). It's basically attempting to convert the duration column in string form to a period column and back.

Would it make sense to check if the string is in that non-numeric display duration format? For instance inside of as.duration() in case as.period() yields NA, or -- if that's too slow -- within C_parse_period().

Edit: Easy ad-hoc workaround for now:

parse_duration <- function(x) {
    as.duration(gsub("\\s\\((.*)", "", x))

Applied to the example above:

(x <- duration(1, "years")  # [1] "31557600s (~1 years)"
(y <- as.character(x))      # [1] "31557600s (~1 years)"
(z <- as.duration(y))       # [1] NA
(z <- parse_duration(y))    # [1] "31557600s (~1 years)"
(is.duration(z))            # [1] TRUE

@vspinu vspinu closed this as completed in 46d8d19 Jan 12, 2022
Copy link

vspinu commented Jan 12, 2022

Thanks or bringing it up.

netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this issue Jun 5, 2023
Version 1.9.2


* [#1104](tidyverse/lubridate#1104) Fix
  incorrect parsing of months when %a format is present.


* Adapt to internal name changes in R-devel

Version 1.9.1


* `as_datetime()` accepts multiple formats in format argument, just like `as_date()` does.


* [#1091](tidyverse/lubridate#1091) Fix
  formatting of numeric inputs to parse_date_time.

* [#1092](tidyverse/lubridate#1092) Fix
  regression in `ymd_hm` on locales where `p` format is not defined.

* [#1097](tidyverse/lubridate#1097) Fix
  `as_date("character")` to work correctly with formats that include
  extra characters.

* [#1098](tidyverse/lubridate#1098) Roll
  over the month boundary in `make_dateime()` when units exceed their
  maximal values.

* [#1090](tidyverse/lubridate#1090)
  timechange has been moved from Depends to Imports.

Version 1.9.0


* `roll` argument to updating and time-zone manipulation functions is
  deprecated in favor of a new `roll_dst` parameter.

* [#1042](tidyverse/lubridate#1042)
  `as_date` with character inputs accepts multiple formats in `format`
  argument. When `format` is supplied, the input string is parsed with
  `parse_date_time` instead of the old `strptime`.

* [#1055](tidyverse/lubridate#1055)
  Implement `as.integer` method for Duration, Period and Interval

* [#1061](tidyverse/lubridate#1061) Make
  `year<-`, `month<-` etc. accessors truly generic. In order to make
  them work with arbitrary class XYZ, it's enough to define a
  `reclass_date.XYZ` method.

* [#1061](tidyverse/lubridate#1061) Add
  support for `year<-`, `month<-` etc. accessors for `data.table`'s
  IDate and ITime objects.

* [#1017](tidyverse/lubridate#1017)
  `week_start` argument in all lubridate functions now accepts full
  and abbreviated names of the days of the week.

* The assignment value `wday<-` can be a string either in English or
  as provided by the current locale.

* Date rounding functions accept a date-time `unit` argument for
  rounding to a vector of date-times.

* [#1005](tidyverse/lubridate#1005)
  `as.duration` now allows for full roundtrip `duration ->
  as.character -> as.duration`

* [#911](tidyverse/lubridate#911) C parsers
  treat multiple spaces as one (just like strptime does)

* `stamp` gained new argument `exact=FALSE` to indicate whether
  `orders` argument is an exact strptime formats string or not.

* [#1001](tidyverse/lubridate#1001) Add
  `%within` method with signature (Interval, list), which was
  documented but not implemented.

* [#941](tidyverse/lubridate#941)
  `format_ISO8601()` gained a new option `usetz="Z"` to format time
  zones with a "Z" and convert the time to the UTC time zone.

* [#931](tidyverse/lubridate#931) Usage of
  `Period` objects in rounding functions is explicitly documented.


* [#1036](tidyverse/lubridate#1036)
  `%within%` now correctly works with flipped intervals

* [#1085](tidyverse/lubridate#1085)
  `as_datetime()` now preserves the time zone of the POSIXt input.

* [#1072](tidyverse/lubridate#1072) Names
  are now handled correctly when combining multiple Period or Interval

* [#1003](tidyverse/lubridate#1003)
  Correctly handle r and R formats in locales which have no p format

* [#1074](tidyverse/lubridate#1074) Fix
  concatination of named Period, Interval and Duration vectors.

* [#1044](tidyverse/lubridate#1044) POSIXlt
  results returned by `fast_strptime()` and `parse_date_time2()` now
  have a recycled `isdst` field.

* [#1069](tidyverse/lubridate#1069) Internal
  code handling the addition of period months and years no longer
  generates partially recycled POSIXlt objects.

* Fix rounding of POSIXlt objects

* [#1007](tidyverse/lubridate#1007) Internal
  lubridate formats are no longer propagated to stamp formater.

* `train` argument in `parse_date_time` now takes effect. It was
  previously ignored.

* [#1004](tidyverse/lubridate#1004) Fix
  `c.POSIXct` and `c.Date` on empty single POSIXct and Date vectors.

* [#1013](tidyverse/lubridate#1013) Fix
  c(`POSIXct`,`POSIXlt`) heterogeneous concatenation.

* [#1002](tidyverse/lubridate#1002) Parsing
  only with format `j` now works on numeric inputs.

* `stamp()` now correctly errors when no formats could be guessed.

* Updating a date with timezone (e.g. `tzs = "UTC"`) now returns a POSIXct.


* `lubridate` is now relying on `timechange` package for update and
  time-zone computation. Google's CCTZ code is no longer part of the

* `lubridate`'s updating logic is now built on top of `timechange`

* Change implementation of `c.Period`, `c.Duration` and `c.Interval`
  from S4 to S3.

Version 1.8.0


* [#960](tidyverse/lubridate#960)
  `c.POSIXct` and `c.Date` can deal with heterogeneous object types
  (e.g `c(date, datetime)` works as expected)


* [#994](tidyverse/lubridate#994)
  Subtracting two duration or two period objects no longer results in
  an ambiguous dispatch note.

* `c.Date` and `c.POSIXct` correctly deal with empty vectors.

* `as_datetime(date, tz=XYZ)` returns the date-time object with HMS
  set to 00:00:00 in the corresponding `tz`


* [#966](tidyverse/lubridate#966) Lubridate is
  now built with cpp11 (contribution of @DavisVaughan)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

No branches or pull requests

3 participants