I am working on a project where I am required to record and track the received date and time of emails. This is a snippet of the code that I have.
library(RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
OutlookNameSpace <- OutApp$GetNameSpace("MAPI")
folderName <- "Inbox"
folder <- OutlookNameSpace$Folders(1)$Folders(folderName)
emails <- folder$Items
I can obtain the received date of each email (e.g. 2020-07-17) with ReceivedTime()
as.Date(emails(1)$ReceivedTime(), origin = "1899-12-30")
But, how can I get the hour, min, sec components of the received time?
Thank you.
I suspect that 44029.7004451092 is simply a fraction of the number of days since 1900. So, if you can access that number (I'm not sure how, as I don't have access to Outlook emails, but it shouldn't be too hard to access it from the object), then we can write a function to extract the time.
For example, assume you've extracted that .Data
string: '44029.7004451092'
.
We can pass that into a custom function. This function basically splits the string up into two parts. The first part is the day (i.e., 44029). That's where we get the date from. The second part is the series of digits after the period, which I'm assuming is meant to refer to the fraction of the day. (For example, 0.5 would be 12 pm.)
We can then just do some simple arithmetic to figure out how many hours, minutes and seconds are in that fraction, based on the number of seconds in a day. Then we wrap it all up, and return a POSIXct object.
get_time_from_date <- function(x, day_seconds = 86400) {
day_fraction <- as.numeric(paste0('0.', strsplit(x, '\\.')[[1]][2]))
num_seconds <- day_fraction * day_seconds
day_hour <- num_seconds %/% 3600
day_min <- num_seconds %% 3600 %/% 60
day_sec <- num_seconds %% 3600 %% 60
actual_date <- as.Date(as.numeric(strsplit(x, '\\.')[[1]][1]), origin = "1899-12-30")
return(as.POSIXct(paste0(actual_date, ' ', day_hour, ':', day_min, ':', day_sec)))
}
get_time_from_date('44029.7004451092')
# [1] "2020-07-17 16:48:38 NZST"
The timezone will be dependent on your system. I have no way of verifying whether this is correct or not, but hopefully it works for you.