tz() Function of lubridate Package in R (2 Examples) | Time Zone Component

 

In this R tutorial you’ll learn how to set and query the time zone of a date and time object using the tz function of the lubridate package.

Table of contents:

With that, here’s how to do it…

 

Example Data & Software Packages

The following data is used as basement for this R programming tutorial:

my_time <- as.POSIXlt("2022-10-05 10:35:42")    # Create time object
my_time                                         # Print time object
# [1] "2022-10-05 10:35:42 CEST"

The previous output of the RStudio console shows that our example data is a date and time object with the POSIXlt class.

To be able to use the commands and functions of the lubridate package, we also have to install and load lubridate:

install.packages("lubridate")                   # Install & load lubridate
library("lubridate")

 

Example 1: Change Time Zone Using tz() Function of lubridate Package

In this example, I’ll demonstrate how to set the time zone of a data object using the tz function of the lubridate package.

Have a look at the R programming syntax below:

tz(my_time) <- "UTC"                            # Apply tz function
my_time                                         # Print updated time object
# [1] "2022-10-05 10:35:42 UTC"

As you can see, we have changed the time zone component of our date and time object from CEST to UTC.

 

Example 2: Get Time Zone Using tz() Function of lubridate Package

Example 2 illustrates how to extract the time zone from a date and time object.

For this task, we can apply the tz function as in the following R code:

tz(my_time)                                     # Apply tz function
# [1] "UTC"

The RStudio console returns UTC, i.e. our new time zone.

 

Video & Further Resources

Would you like to learn more about the application of the tz function of the lubridate package? Then you might have a look at the following video on my YouTube channel. In the video tutorial, I’m demonstrating the R codes of this tutorial.

 

The YouTube video will be added soon.

 

Furthermore, you may want to read the related RStudio tutorials on my homepage:

 

Summary: In this article, I have illustrated how to apply the tz function of the lubridate package in the R programming language. Please tell me about it in the comments, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top