Learn R Programming

ds4psy (version 0.4.0)

sample_time: Draw a sample of n random times (from a given range).

Description

sample_time draws a sample of n random times from a given range.

Usage

sample_time(
  n = 1,
  from = "1970-01-01 00:00:00",
  to = Sys.time(),
  as_POSIXct = TRUE,
  tz = ""
)

Arguments

n

Number dates to draw. Default: n = 1.

from

Earliest date (as string). Default: from = "1970-01-01 00:00:00".

to

Latest date (as string). Default: to = Sys.time().

as_POSIXct

Boolean: Return calendar time ("POSIXct") object? Default: as_POSIXct = TRUE. If as_POSIXct = FALSE, a local time ("POSIXlt") object is returned (as a list).

tz

Time zone. Default: tz = "" (i.e., current system time zone, see Sys.timezone()). Use tz = "UTC" for Universal Time, Coordinated.

Details

By default, sample_time draws n = 1 random calendar time (as a "POSIXct" object) in the range from = "1970-01-01 00:00:00" to = Sys.time() (current time).

If as_POSIXct = FALSE, a local time ("POSIXlt") object is returned (as a list).

The tz argument allows specifying time zones (see Sys.timezone() for current setting and OlsonNames() for options.)

See Also

Other sampling functions: coin(), dice_2(), dice(), sample_char(), sample_date()

Examples

Run this code
# NOT RUN {
# Basics:
sample_time()
sample_time(n = 10)

# Specific ranges:
sort(sample_time(n = 10, from = (Sys.time() - 60)))  # within the last minute
sort(sample_time(n = 10, from = (Sys.time() - 1 * 60 * 60)))  # within the last hour
sort(sample_time(n = 10, from = Sys.time(), 
                           to = (Sys.time() + 1 * 60 * 60)))  # within the next hour
sort(sample_time(n = 10, from = "2020-12-31 00:00:00 CET", 
                           to = "2020-12-31 00:00:01 CET"))   # within 1 sec range
                           
# Local time (POSIXlt) objects (as list):
sample_time(as_POSIXct = FALSE)
unlist(sample_time(as_POSIXct = FALSE))

# Time zones:
sample_time(n = 3, tz = "UTC")
sample_time(n = 3, tz = "US/Pacific")
 
# Note: Oddity with sample(): 
sort(sample_time(n = 10, from = "2020-12-31 00:00:00 CET", 
                           to = "2020-12-31 00:00:00 CET"))  # range of 0!
# see sample(9:9, size = 10, replace = TRUE)

# }

Run the code above in your browser using DataLab