parttime
parttime copied to clipboard
Allow casting from `Date` and `POSIXt` objects
I think that it would be useful to be able to cast Date and POSIXt objects to parttime objects.
My initial thought would be something like the following:
library(parttime)
#> Warning: package 'parttime' was built under R version 4.3.3
#> Initializing default timezone offset, which is assumed when timezone
#> parts are missing.
#>
#> options("parttime.assume_tz_offset" = 0L)
#>
#> Attaching package: 'parttime'
#> The following objects are masked from 'package:stats':
#>
#> end, start
#> The following objects are masked from 'package:base':
#>
#> pmax, pmin
as.parttime("2001")
#> <partial_time<YMDhms+tz>[1]>
#> [1] "2001"
as.parttime(as.Date("2001-01-01"), missing_year = FALSE, missing_month = TRUE, missing_day = TRUE)
#> Error in vctrs::stop_incompatible_cast(x, to): argument "x_arg" is missing, with no default
Created on 2024-05-15 with reprex v2.1.0
Note you can cast Date and POSIXt objects to {parttime} objects using {datetimeoffset} as an intermediary:
Sys.Date() |>
datetimeoffset::as_datetimeoffset() |>
parttime::as.parttime()
<partial_time<YMDhms+tz>[1]>
[1] "2024-05-15"
Sys.time() |>
datetimeoffset::as_datetimeoffset() |>
parttime::as.parttime()
<partial_time<YMDhms+tz>[1]>
[1] "2024-05-15 11:09:56.833+-7:00"
And if you prefer not to pull in new dependencies, you can also go through an as.character intermediate - though you may have to juggle things like timezones and formatting.
Sys.Date() |>
as.character() |>
parttime::as.parttime()
or
Sys.Date() |>
as.POSIXct() |>
as.character() |>
parttime::as.parttime()
Even with a work-around available, I do agree that handling coercion from common base types should be handled out of the box.
Thanks for filing the report.