System date and time in R

R introduction R basics
System date and time in R

R provides several functions to get the system date and time, such as the sys.Date(), Sys.time() and date(). In the following sections we will review their differences and use cases.

Current date with Sys.Date()

The Sys.Date() function provides the current date showing the current year, month and day separated by a hyphens in the current time zone. The output of the function is of class "Date".


However, you can customize the format of the date making use of the format function. For instance, if you want your date in day-month-year format you can do the following:

format(Sys.Date(), "%d-%m-%Y")

Note that you can add or subtract days to the function. For instance, if you want to know which day was 30 days ago you can subtract 30 to the date:

Sys.Date() - 30

Current time with Sys.time()

The Sys.time function returns the date and time in a specific time zone. The class of the output provided by this function is "POSIXct".

"2023-11-12 18:10:10 CET"

This function is really useful to calculate approximately how long it takes for a code to run storing the time before and after a code runs and then calculating the time difference, as shown in the example below:

# Start time
start <- Sys.time()

# Code

# End time
end <- Sys.time()

# Elapsed time
end - start
Time difference of 0.001152 secs

A similar function to calculate the time a code takes is system.time.

System date and time with date()

The date function returns a character string, so you won’t be able to customize its format or perform operations with it and the day and month abbreviations will be always in English.

"Sun Nov 12 18:10:25 2023"