Convert POSIXct Date & Time to UNIX Epoch Timestamp in R (Example)
In this post you’ll learn how to convert dates and times to UNIX timestamps in the R programming language.
The article will contain the following:
Let’s take a look at some R codes in action.
Introducing Example Data
Have a look at the following example data:
my_datetime <- Sys.time() # Create example date & time my_datetime # Print date & time #  "2022-04-19 13:45:23 UTC"
As you can see based on the previous output of the RStudio console, our example data is a date and time object with the class POSIXct.
Example: Convert POSIXct Date & Time to UNIX Timestamp Using as.numeric() Function
This example shows how to transform a POSIXct date and time object to a UNIX timestamp.
To accomplish this task, we can use the as.numeric function as shown in the following R code:
my_timestamp <- as.numeric(my_datetime) # Convert date & time to timestamp my_timestamp # Print timestamp #  1650375923
As you can see, the UNIX timestamp that corresponds to our example date and time is 1650375923.
Video & Further Resources
Would you like to learn more about the switching from dates and times to UNIX timestamps? Then you may want to have a look at the following video instruction on my YouTube channel. I’m explaining the contents of this page in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you might have a look at the other articles on my website.
- Convert Date to Numeric Time Object
- Convert Data Frame with Date Column to Time Series Object
- Convert Year, Month, Day, Hour, Minutes & Seconds to Date & Time
- Convert UNIX Timestamp to Date Object
- All R Programming Examples
In this R tutorial you have learned how to handle epoch timestamps, or more precisely, how to transform dates and times to UNIX timestamps. Tell me about it in the comments below, if you have any further questions.
Statistics Globe Newsletter