Converting time format to numeric with R

Frank Wang picture Frank Wang · Jan 16, 2012 · Viewed 44.7k times · Source

In most cases,we convert numeric time to posixct format using R. However, sometimes, we want to compare which time point is earlier, then we would prefer the numeric time format. Thus, it's quite practical question to convert time format to numeric. For example,I have the data format like "2001-03-13 10:31:00",

  begin <- "2001-03-13 10:31:00"

Using R, I want to figure out how to covert it into a numeric, e.g. the Julian time, something like the passing seconds between 1970-01-01 00:00:00 and 2001-03-13 10:31:00.

Do you have any suggestions?


The Julian calendar began in 45 BC (709 AUC) as a reform of the Roman calendar by Julius Caesar. It was chosen after consultation with the astronomer Sosigenes of Alexandria and was probably designed to approximate the tropical year (known at least since Hipparchus). see http://en.wikipedia.org/wiki/Julian_calendar

Answer

IRTFM picture IRTFM · Jan 16, 2012

If you jsut want to remove ":" , " ", and "-" from a character vector then this will suffice:

end <- gsub("[: -]", "" , begin, perl=TRUE)
#> end
#[1] "20010313103100"

You should read the section about 1/4 of the way down in ?regex about character classes. Since the "-" is special in that context as a range operator, it needs to be placed first or last.

After your edit then the answer is clearly what @joran wrote, except that you would need first to convert to a DateTime class:

 as.numeric(as.POSIXct(begin))
#[1] 984497460

The other point to make is that comparison operators do work for Date and DateTime classed variables so the conversion may not be necessary at all. This compares 'begin' to a time one second later and correctly reports that begin is earlier:

as.POSIXct(begin) < as.POSIXct(begin) +1
 #[1] TRUE