简体   繁体   中英

Consistent output of as.character for date objects in R

An external R library uses the as.character function to convert objects of different classes to strings. That works fine except for my date objects (classes "POSIXlt" and "POSIXt"): Normally the output is like "2010-11-04 10:43:00" (which is perfect) but every time when time is 00:00:00 (midnight) the time component is ommited and only the date component is shown like "2010-11-04". But for further processing I need a consistent output format. So the time component should be displayed in any case.

I can't simply use the format function because the external library does the call. So I thought that overwriting the as.character function for the classes "POSIXlt" and "POSIXt" could be a solution but I don't know how. Other ideas are welcome :)

You can overwrite the as.character method for POSIXct objects simply by creating your own.

as.character.POSIXct <- function(x, format="%Y-%m-%d %H:%M:%S", ...)
format(x, format=format, ...)

In this case though, there is no existing as.character.POSIXct so you're not actually overwriting anything. You are , however, overriding the default as.character.POSIXt method, which is what would be called in the absence of a POSIXct method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM