How to Convert UNIX Timestamp to Date in R (3 Methods)


You can use one of the following three methods to convert a UNIX timestamp to a date object in R:

Method 1: Use Base R

#convert UNIX timestamp to date 
as.Date(as.POSIXct(x, origin="1970-01-01"))

Method 2: Use anytime Package

library(anytime)

#convert UNIX timestamp to date
anydate(x)

Method 3: Use lubridate Package

library(lubridate)

#convert UNIX timestamp to date 
as_date(as_datetime(x))

The following examples show how to use each function in practice.

Example 1: Convert Timestamp to Date Using Base R

We can use the following code to convert a UNIX timestamp to a date using only functions from base R:

#define UNIX timestamp
value <- 1648565400

#convert UNIX timestamp to date object
new_date <- as.Date(as.POSIXct(value, origin="1970-01-01"))

#view date object
new_date

[1] "2022-03-29"

#view class of date object
class(new_date)

[1] "Date"

The UNIX timestamp has successfully been converted to a date object.

Example 2: Convert Timestamp to Date Using anytime Package

We can also use the anydate() function from the anytime package to convert a UNIX timestamp to a date object in R:

library(anytime)

#define UNIX timestamp
value <- 1648565400

#convert UNIX timestamp to date object
new_date <- anydate(value)

#view date object
new_date

[1] "2022-03-29"

#view class of date object
class(new_date)

[1] "Date"

The UNIX timestamp has successfully been converted to a date object.

Example 3: Convert Timestamp to Date Using lubridate Package

We can also use the as_date() function from the lubridate package to convert a UNIX timestamp to a date object in R:

library(lubridate)

#define UNIX timestamp
value <- 1648565400

#convert UNIX timestamp to date object
new_date <- as_date(as_datetime(value))

#view date object
new_date

[1] "2022-03-29"

#view class of date object
class(new_date)

[1] "Date"

Once again, the UNIX timestamp has successfully been converted to a date object.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Convert a Character to a Timestamp in R
How to Convert Factor to Date in R
How to Extract Year from Date in R

Leave a Reply

Your email address will not be published. Required fields are marked *