Created
January 14, 2018 20:14
-
-
Save tjvananne/e24d4a0ffad8e6e73f7dcddd9c31db3c to your computer and use it in GitHub Desktop.
R Date Timestamp Epoch Unix Time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(lubridate) # <3 tidyverse | |
# this is likely not the most efficient way to generate unix time stamps, but it is intuitive to me | |
# I like to see how it is done step by step | |
# to make this more efficient, you could store the "epoch" value outside the function so it | |
# doesn't have to be calculated every time you call the function | |
time_since_epoch <- function() { | |
x1 <- as.POSIXct(Sys.time()) | |
x2 <- format(x1, tz="GMT", usetz=F) | |
x3 <- lubridate::ymd_hms(x2) | |
epoch <- lubridate::ymd_hms('1970-01-01 00:00:00') | |
time_since_epoch <- (x3 - epoch) / dseconds() | |
return(time_since_epoch) | |
} | |
# helper timestamp function - generating timestamps that are compatible with Amazon's Product Advertising API | |
gen_utc_ts <- function(ts) { | |
# x1: timestamp in current system timezone | |
# x2: format with tz argument changes the timezone to GMT/UTC | |
# x3: lubridate objects are easier to work with and manipulate | |
x1 <- as.POSIXct(ts) | |
x2 <- format(x1, tz = "GMT", usetz = F) | |
x3 <- lubridate::ymd_hms(x2) | |
# reformat the string manually (kinda sloppy, but lots of control) | |
return(paste0( | |
sprintf("%04d", lubridate::year(x3)), '-', | |
sprintf("%02d", lubridate::month(x3)), '-', | |
sprintf("%02d", lubridate::day(x3)), 'T', | |
sprintf("%02d", lubridate::hour(x3)), ':', | |
sprintf("%02d", lubridate::minute(x3)), ':', | |
sprintf("%02d", lubridate::second(x3)), 'Z')) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment