Adding timezone to POSIXct object in data.table
Asked Answered
P

1

5

I have a data.table object with the columns date and time stored as IDate/ITime objects. I also have a time zone column where the time zone is given as character.

Now I want to create a column DateTime that is using the POSIXct format. However I can't figure out how to add the correct time zone to the object.

#Create the data.table object
dtData <- data.table(
Index = seq(1,5), 
Time= as.ITime(c('16:00', '16:00', '12:30', '16:00', '15:00')),
Date = as.IDate(rep('2015-05-28', 5)),
TimeZone=c('America/New_York', 'America/New_York', 'Europe/London', 'Asia/Hong_Kong', 'Japan'))

#This gives an error of invalid tz value
dtData[, psxDateTime:=as.POSIXct(Date, time = Time, tz = TimeZone)]

#This seem to set every row to Japan time zone
dtData[, psxDateTime:=as.POSIXct(Date, time = Time, tz = TimeZone), by=Index]
print(dtData$psxDateTime)

Would anyone be able to point me in the right direction? Thanks.

EDIT:

After reading the comments by David Arenburg and akrun it looks like that there is no way to store POSIXct objects with different time zones in one data.table column. Even combining a vector changes the time zone attribute:

Date1 <- as.POSIXct('2015-05-28 16:00', tz='America/New_York')
Date2 <- as.POSIXct('2015-05-28 12:00', tz='Japan')
Date3 <- c(Date1, Date2)
print(Date1)
print(Date2)
print(Date3)
Psoriasis answered 28/5, 2015 at 12:23 Comment(4)
What's time = Time? Can't recall a time parameter in as.POSIXct I also doubt that a single POSIXct vector can contain different time zones simultaneously.Adown
This comes from the data.table class IDateTime. See inside-r.org/packages/cran/data.table/docs/as.IDate However dtData[, psxDateTime:=as.POSIXct(paste(Date, Time), tz=cTimeZone), by=Index] does not work either.Psoriasis
It should work, but as I mentioned, I doubt you can have multiple time zones in a single veector.Adown
As @DavidArenburg mentioned, if you need multiple time zones, split it to list and store them as list elements.Scrouge
P
1

I am closing this question as it seems like it is not possible to have POSIXct objects with different time zones in one column of a data.table.

Psoriasis answered 28/5, 2015 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.