Reputation: 3125
I don't understand why this doesn't work:
as.Date('2001-10-26 10:00:00', format='%Y-%m-%d %H:%M:%S')
It returns
"2001-10-26"
but I expected it to be
"2001-10-26 10:00:00"
.
I don't need anything complicated; just to convert a string to a date with a timestamp. Not sure why the format argument isn't working.
Thanks.
Upvotes: 3
Views: 2254
Reputation: 7190
R has several ways (expressed in classes) to deal with time and dates. In your fist code you are using the as.Date
function that converts its arguments to Date
class. The string you are providing to that function contains also other elements that do not belong to Date
class and as a result it prints only elements that the function is allowed to handle. As you can read in the documentation:
... (dates)... They are always printed following the rules of the current Gregorian calendar, even though that calendar was not in use long ago (it was adopted in 1752 in Great Britain and its colonies).
the informations are essentially lost. See here:
a <- as.Date('2001-10-26 10:00:00', format='%Y-%m-%d %H:%M:%S')
format(a, format='%Y-%m-%d %H:%M:%S')
[1] "2001-10-26 00:00:00"
If you want to keep informations about the time and not only the dates you have to use a format that is able to store that informations. The classes are POSIXct
and POSIXlt
where the first one is just a huge integer that counts the seconds since 1970-01-01 and the second one is just a list where each element stores seconds, days, months etc.
The functions (in base R) you have to use are: strptime
(as pointed out in comments by @nongkrong), or as.POSIXlt
or as.POSIXct
.
There are other functions in other packages (like chron
and lubridate
) but putting aside special classes developed by single packages (like period
in lubridate
) the key classes are the ones I've just illustrated here.
Upvotes: 4