Epoch in R Programming Language

Here’s the translated code and explanation in R, formatted in Markdown suitable for Hugo:

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in R.

# Use Sys.time() to get the current time
now <- Sys.time()
print(now)

# Convert to seconds since the Unix epoch
print(as.numeric(now))

# Convert to milliseconds since the Unix epoch
print(as.numeric(now) * 1000)

# Convert to nanoseconds since the Unix epoch
print(as.numeric(now) * 1e9)

# Convert back from seconds since the Unix epoch
print(as.POSIXct(as.numeric(now), origin="1970-01-01"))

# Convert back from nanoseconds since the Unix epoch
print(as.POSIXct(as.numeric(now), origin="1970-01-01"))

To run the program, save it as epoch.R and use Rscript:

$ Rscript epoch.R
[1] "2023-06-08 10:15:30 UTC"
[1] 1686220530
[1] 1686220530000
[1] 1686220530000000000
[1] "2023-06-08 10:15:30 UTC"
[1] "2023-06-08 10:15:30 UTC"

In R, we use Sys.time() to get the current time. The as.numeric() function can be used to convert this time to seconds since the Unix epoch. To get milliseconds or nanoseconds, we multiply this value by 1000 or 1e9 respectively.

To convert back from seconds or nanoseconds since the epoch to a time object, we use as.POSIXct() with the origin parameter set to “1970-01-01” (the Unix epoch).

Note that R doesn’t have built-in functions for milliseconds or nanoseconds precision like some other languages, so we perform the conversion manually.

Next, we’ll look at another time-related task: time parsing and formatting.