Reputation: 739
I have got a netcdf
file to extract some variables from it. the provider told me that the time variable (A) is hours since 1900-01-01 00:00:0.0
. I need to convert this variable to a normal date and write to another txt file.
f1 <- open.ncdf("C:\\Users\\data.nc")
# [1] "file C:\\Users\\data.nc has 3 dimensions:"
# [1] "longitude Size: 2"
# [1] "latitude Size: 2"
# [1] "time Size: 2920"
# [1] "file C:\\Users\\data.nc has 5 variables:"
# [1] "short stm[longitude,latitude,time] Longname:soil textre Missval:-32767"
time:
A <- get.var.ncdf(nc=f1,varid="time")
head(A)
## [1] 990552 990558 990564 990570 990576 990582
another variable:
B1 <- get.var.ncdf(nc=f,varid="stm")
write.table(t(rbind(A,B1)),file="output.txt")
I need your help to convert the time variable to a normal date before writing to the text output file.
Upvotes: 2
Views: 1210
Reputation: 92300
Date
If A
are hours since "1900-01-01"
, just divide them by 24, and pass this date into the origin
parameter within the as.Date
function, as in
A <- c(990552, 990558, 990564, 990570, 990576, 990582)
as.Date(A/24, origin = "1900-01-01")
## [1] "2013-01-01" "2013-01-01" "2013-01-01" "2013-01-01" "2013-01-02" "2013-01-02"
Date + time
If you want the hours too, use as.POSIXct
instead and multiply by 3600 (You should probably specify your time zone too within tz
parameter)
as.POSIXct(A*3600, origin = "1900-01-01")
## [1] "2013-01-01 02:00:00 IST" "2013-01-01 08:00:00 IST" "2013-01-01 14:00:00 IST" "2013-01-01 20:00:00 IST" "2013-01-02 02:00:00 IST" "2013-01-02 08:00:00 IST"
Time zone
In order to know your time zone, type
Sys.timezone()
For a full list of possible time zones, type
OlsonNames()
Adding/Removing hours
Either way, you can remove/add hours by multiplying the number of hours by 3600
and adding/removing from the results, for example
as.POSIXct(A*3600, origin = "1900-01-01") - 2*3600
Upvotes: 7