Get current time including seconds from Sys.Date() in R

Btibert3 picture Btibert3 · Dec 16, 2011 · Viewed 18.1k times · Source

I am sure this is pretty basic, but I am not able to extract various peices of time from the system date. Simply, I am not sure why I can not accurately extract the current minutes and seconds using %M or %S. Any thoughts?

It currently is 12:38 pm on my machine.

> format(Sys.Date(), "%c")
[1] "12/16/2011 12:00:00 AM"

> R.Version()
$platform
[1] "i386-pc-mingw32"

$arch
[1] "i386"

$os
[1] "mingw32"

$system
[1] "i386, mingw32"

$status
[1] ""

$major
[1] "2"

$minor
[1] "14.0"

$year
[1] "2011"

$month
[1] "10"

$day
[1] "31"

$`svn rev`
[1] "57496"

$language
[1] "R"

$version.string
[1] "R version 2.14.0 (2011-10-31)"

Answer

Josh O'Brien picture Josh O'Brien · Dec 16, 2011

For this, you probably want to use Sys.time() instead of Sys.Date().

format(Sys.time(), "%S")

Sys.Date returns a Date object that's essentially a character string of a form like "YYYY-MM-DD". It does not record hours, minutes, or seconds.

(This was slightly hidden from you in your call to format(Sys.Date, "%S") because that dispatched a method, format.Date that converts the Date object to a POSIXlt object that does have hours, minutes, and seconds. In that conversion, the Date object is treated as if it represents a time at midnight GMT -- hence the value of "00" it always returns for its seconds element.)