Time in R Programming Language

# R offers extensive support for times and durations;
# here are some examples.

library(lubridate)

# We'll start by getting the current time.
now <- Sys.time()
print(now)

# You can build a time object by providing the
# year, month, day, etc. Times are always associated
# with a time zone.
then <- ymd_hms("2009-11-17 20:34:58.651387237", tz = "UTC")
print(then)

# You can extract the various components of the time
# value as expected.
print(year(then))
print(month(then))
print(day(then))
print(hour(then))
print(minute(then))
print(second(then))
print(tz(then))

# The day of the week is also available.
print(wday(then, label = TRUE))

# These functions compare two times, testing if the
# first occurs before, after, or at the same time
# as the second, respectively.
print(then < now)
print(then > now)
print(then == now)

# The interval function returns a Duration representing
# the interval between two times.
diff <- interval(then, now)
print(diff)

# We can compute the length of the duration in
# various units.
print(as.duration(diff))
print(as.period(diff))

# You can use + to advance a time by a given
# duration, or with a - to move backwards by a
# duration.
print(then + diff)
print(then - diff)

To run this R script, save it to a file (e.g., time_example.R) and execute it using the R interpreter:

$ Rscript time_example.R

This R script demonstrates various time-related operations using the lubridate package, which provides a comprehensive set of tools for working with dates and times in R. The script covers creating time objects, extracting components, comparing times, calculating durations, and performing time arithmetic.

Note that R’s datetime handling is somewhat different from Go’s, but the lubridate package provides similar functionality. The exact output will depend on when you run the script, but it will show the current time, the specified time in 2009, various time components, comparisons, and duration calculations.

R doesn’t have built-in nanosecond precision, so some of the very fine-grained operations from the Go example are not directly translatable. However, the lubridate package provides precise time handling capabilities suitable for most practical applications.