I want to parse a character with a 5-digit (or more) year, e.g. 10000-01-01 01:00:00 to class POSIXct.
A 4-digit year is of course no problem. For example,
as.POSIXct("1000-01-01 01:00:00")
But with a 5-digit year, e.g. 10000, as.POSIXct errors:
as.POSIXct("10000-01-01 01:00:00")
# Error in as.POSIXlt.character(x, tz, ...) :
# character string is not in a standard unambiguous format
I wonder is there a way to handle year with more than 4 digits in R?
There is no problem handling years with 5 digits, it's the
as.POSIXct.characterfunction that is the problem here, since it usesstrptime, which can only handle years 0-9999.The following code produces a POSIXct object of the correct date/time:
If you use
POSIXltto construct the date-times, you can assign the year part numerically, then convert to POSIXct, which allows the following function to be defined. It will do the same asas.POSIXctbut can handle large years:For example: