I have imported data in R from an Excel sheet with package readxl.
The sheet contains a column with dates. These dates behave like dates in Excel (I can change the date formatting in Excel).
Directly after importing in R with readxl the format is this:
# A tibble: 1 x 1
`datum`
<dttm>
1 2010-01-20 21:00:00
My goal is to use the lubridate function days_in_month on the imported dates.
lubridate::days_in_month(df[2,1])
Although using this function gives this error:
Error in as.POSIXlt.default(x, tz = tz(x)) :
do not know how to convert 'x' to class “POSIXlt”
I did serveral test to identify the format:
is.Date(df[2,1])
is.POSIXt(df[2,1])
is.instant(df[2,1])
All give result FALSE.
If I print one date I receive this result:
# A tibble: 1 x 1
`datum`
<dttm>
1 2010-01-20 21:00:00
I have tried several conversions:
df$datum <- as.Date(df$datum, origin = "1899-12-30")
df$datum <- as.Date(as.POSIXct(df$datum, 'GMT'))
df$datum <- as.Date(df$datum, format='%Y-%m-%d')
Although the results of the tests above after conversion are all FALSE.
If I do the first conversion as.Date(df$datum, origin = "1899-12-30"). After this the outcome of print is:
# A tibble: 1 x 1
`datum`
<date>
1 2010-01-20
df$datum + 60 gives:
1 2010-03-21
So it seems it is behaving as a date since I can add 60.
Although all the test give FALSE and days_in_month from lubridate still gives the error above.
How can I convert the date into a correct format which lubridate can process?
Thanks a lot!
"2010-01-20 21:00:00"
is not a date, it's a date-time. If you want it to be aDate
, I suggest you either (1) convert to time then date, withas.Date(as.POSIXct(...))
; or (2) truncate the string and convert, something likeas.Date(gsub(" .*", "", df$datum))
oras.Date(substr(df$datum, 1, 10))
. – r2evansdf$datum
above is alreadyPOSIXt
, soas.Date
just works. And it seems like the problem you're having is with code and data that we do not have. Can you provide the output fromdput(head(df$datum))
and the code you're using that is generating the error? I see no calls tolubridate::
in your code. – r2evansdatum
= structure(14629, class = "Date")), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame")) – user2165379