I am wanting to convert date-times stored as characters to date-time objects. However if a date time includes midnight then the resulting datetime object excludes the time component, which then throws an error when used in a later function (not needed here - but a function that extracts weather data for specified location and date-time).
Example code:
example.dates <- c("2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
posix.dates <- as.POSIXct(example.dates, tz="GMT", format="%Y-%m-%d %H:%M:%S")
posix.dates
posix.dates[2]
NB times is only excluded when the datetime containing midnight is called on it's own (atomic vector).
Is there a way of retaining the time data for midnight times? Can you suggest an alternative function?
format(posix.dates, '%Y-%m-%d %M:%H')
– Bastiastrptime(posix.dates, "%Y-%m-%d %H:%M:%S",'UTC')
, the results are fine and as expected. What is the actual error message? – Bastiastrptime
onPOSIXct
values. If you want to convert toPOSIXlt
,as.POSIXlt
is better. If you want to usestrptime
, then first do the conversion tocharacter
yourself like this:strptime(format(posix.dates[2], "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S", "UTC")
– Distinctly