Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将netcdf时间变量转换为R日期对象

将netcdf时间变量转换为R日期对象
EN

Stack Overflow用户
提问于 2017-09-01 05:43:48
回答 3查看 7.6K关注 0票数 8

我有一个带有timeseries的netcdf文件,时间变量具有以下典型的元数据:

代码语言:javascript
运行
AI代码解释
复制
    double time(time) ;
            time:standard_name = "time" ;
            time:bounds = "time_bnds" ;
            time:units = "days since 1979-1-1 00:00:00" ;
            time:calendar = "standard" ;
            time:axis = "T" ;

在R内部,我想将时间转换为R日期对象。目前,我以硬连接的方式实现了这一点,方法是读取单元属性并拆分字符串,并使用第三个条目作为我的来源(因此假设间隔为“天”,时间为00:00等等):

代码语言:javascript
运行
AI代码解释
复制
require("ncdf4")
f1<-nc_open("file.nc")
time<-ncvar_get(f1,"time")
tunits<-ncatt_get(f1,"time",attname="units")
tustr<-strsplit(tunits$value, " ")
dates<-as.Date(time,origin=unlist(tustr)[3])

这个硬连接解决方案适用于我的具体示例,但我希望R中可能有一个包,它很好地处理时间单位的工发组织and netcdf日期约定,并将它们安全地转换为R date对象?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-12 09:11:48

我刚刚发现(在贴出这个问题两年后!)有一个名为ncdf.tools的包,它具有以下功能:

convertDateNcdf2R

哪一个

从指定的netCDF文件或朱利安日(或秒、分钟、小时)向量转换为POSIXct R向量的时间向量。

使用:

代码语言:javascript
运行
AI代码解释
复制
convertDateNcdf2R(time.source, units = "days", origin = as.POSIXct("1800-01-01", 
    tz = "UTC"), time.format = c("%Y-%m-%d", "%Y-%m-%d %H:%M:%S", 
    "%Y-%m-%d %H:%M", "%Y-%m-%d %Z %H:%M", "%Y-%m-%d %Z %H:%M:%S"))

参数:

代码语言:javascript
运行
AI代码解释
复制
time.source 

数字向量或netCDF连接:从原点开始的时间单位或netCDF文件连接,在后一种情况下,时间向量是从netCDF文件中提取出来的,这个文件,特别是时间变量,必须遵循CF netCDF约定。

代码语言:javascript
运行
AI代码解释
复制
units   

字符串:时间源的单位。如果源是netCDF文件,则忽略该值并从该文件读取该值。

代码语言:javascript
运行
AI代码解释
复制
origin  

POSIXct对象:时间源的来源或日/小时为零。如果源是netCDF文件,则忽略该值并从该文件读取该值。

因此,只需将netcdf连接作为第一个参数传递就足够了,而函数则处理其余的参数。警告:这只有在netCDF文件遵循 CF公约 (例如,如果您的单元是“多年”而不是“秒”或“天”之后)时才能工作。

有关该函数的更多详细信息可在此处获得:https://rdrr.io/cran/ncdf.tools/man/convertDateNcdf2R.html

票数 5
EN

Stack Overflow用户

发布于 2017-09-01 23:53:51

据我所知,没有。我有一个使用lubridate的方便的函数,它与您的基本相同。

代码语言:javascript
运行
AI代码解释
复制
getNcTime <- function(nc) {
    require(lubridate)
    ncdims <- names(nc$dim) #get netcdf dimensions
    timevar <- ncdims[which(ncdims %in% c("time", "Time", "datetime", "Datetime", "date", "Date"))[1]] #find time variable
    times <- ncvar_get(nc, timevar)
    if (length(timevar)==0) stop("ERROR! Could not identify the correct time variable")
    timeatt <- ncatt_get(nc, timevar) #get attributes
    timedef <- strsplit(timeatt$units, " ")[[1]]
    timeunit <- timedef[1]
    tz <- timedef[5]
    timestart <- strsplit(timedef[4], ":")[[1]]
    if (length(timestart) != 3 || timestart[1] > 24 || timestart[2] > 60 || timestart[3] > 60 || any(timestart < 0)) {
        cat("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n")
        warning(paste("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n"))
        timedef[4] <- "00:00:00"
    }
    if (! tz %in% OlsonNames()) {
        cat("Warning:", tz, "not a valid timezone. Assuming UTC\n")
        warning(paste("Warning:", timestart, "not a valid start time. Assuming 00:00:00\n"))
        tz <- "UTC"
    }
    timestart <- ymd_hms(paste(timedef[3], timedef[4]), tz=tz)
    f <- switch(tolower(timeunit), #Find the correct lubridate time function based on the unit
        seconds=seconds, second=seconds, sec=seconds,
        minutes=minutes, minute=minutes, min=minutes,
        hours=hours,     hour=hours,     h=hours,
        days=days,       day=days,       d=days,
        months=months,   month=months,   m=months,
        years=years,     year=years,     yr=years,
        NA
    )
    suppressWarnings(if (is.na(f)) stop("Could not understand the time unit format"))
    timestart + f(times)
}

编辑:您可能还想看看ncdf4.helpers::nc.get.time.series

EDIT2:请注意,新提议的、目前正在开发的可怕的stars包将自动处理日期,有关示例请参阅第一篇博文

EDIT3:另一种方法是直接使用units包,这就是stars所使用的。人们可以这样做:(仍然没有正确地处理日历,我不确定units能不能)

代码语言:javascript
运行
AI代码解释
复制
getNcTime <- function(nc) { ##NEW VERSION, with the units package
    require(units)
    require(ncdf4)
    options(warn=1) #show warnings by default
    if (is.character(nc)) nc <- nc_open(nc)
    ncdims <- names(nc$dim) #get netcdf dimensions
    timevar <- ncdims[which(ncdims %in% c("time", "Time", "datetime", "Datetime", "date", "Date"))] #find (first) time variable
    if (length(timevar) > 1) {
        warning(paste("Found more than one time var. Using the first:", timevar[1]))
        timevar <- timevar[1]
    }
    if (length(timevar)!=1) stop("ERROR! Could not identify the correct time variable")
    times <- ncvar_get(nc, timevar) #get time data
    timeatt <- ncatt_get(nc, timevar) #get attributes
    timeunit <- timeatt$units
    units(times) <- make_unit(timeunit)
    as.POSIXct(time)
}
票数 3
EN

Stack Overflow用户

发布于 2017-09-20 06:59:33

我无法使用@af7的函数来处理我的文件,所以我编写了自己的文件。下面的函数创建一个日期的POSIXct向量,从nc文件中读取开始日期、时间间隔、单位和长度。它适用于许多nc文件(但可能不是每个.)形状或形式。

代码语言:javascript
运行
AI代码解释
复制
 ncdate <- function(nc) {
    ncdims <- names(nc$dim) #Extract dimension names
    timevar <- ncdims[which(ncdims %in% c("time", "Time", "datetime", "Datetime",
                                          "date", "Date"))[1]] # Pick the time dimension
    ntstep <-nc$dim[[timevar]]$len
    tm <- ncvar_get(nc, timevar) # Extract the timestep count
    tunits <- ncatt_get(nc, timevar, "units") # Extract the long name of units
    tspace <- tm[2] - tm[1] # Calculate time period between two timesteps, for the "by" argument 
    tstr <- strsplit(tunits$value, " ") # Extract string components of the time unit
    a<-unlist(tstr[1]) # Isolate the unit .i.e. seconds, hours, days etc.
    uname <- a[which(a %in% c("seconds","hours","days"))[1]] # Check unit
    startd <- as.POSIXct(gsub(paste(uname,'since '),'',tunits$value),format="%Y-%m-%d %H:%M:%S") ## Extract the start / origin date
    tmulti <- 3600 # Declare hourly multiplier for date
    if (uname == "days") tmulti =86400 # Declare daily multiplier for date
    ## Rename "seconds" to "secs" for "by" argument and change the multiplier.
    if (uname == "seconds") {
        uname <- "secs"
        tmulti <- 1 }
    byt <- paste(tspace,uname) # Define the "by" argument
    if (byt == "0.0416666679084301 days") { ## If the unit is "days" but the "by" interval is in hours
    byt= "1 hour"                       ## R won't understand "by < 1" so change by and unit to hour.
    uname = "hours"}
    datev <- seq(from=as.POSIXct(startd+tm[1]*tmulti),by= byt, units=uname,length=ntstep)
}

编辑

为了解决@af7注释中强调的上述代码只适用于有规则间隔的文件的缺陷,可以将datev计算为

代码语言:javascript
运行
AI代码解释
复制
 datev <- as.POSIXct(tm*tmulti,origin=startd)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46001573

复制
相关文章
python将日期转换为时间戳_python – 将日期时间转换为时间戳,然后再返回
>>> local = datetime(2014, 1, 30, 23, 59, 40, 1999)
用户7886150
2021/01/19
3.7K0
JS将日期转换为时间戳
1.getTime() 精确到毫秒 let date = new Date() let timeStamp = date.getTime() console.log(timeStamp) // 1606704849115 2.valueOf() 精确到毫秒 let date = new Date() let timeStamp = date.valueOf() console.log(timeStamp) // 1606704906237 3.parse() 精确到秒,毫秒会用000替代 let date
peng_tianyu
2022/12/15
13.7K0
js将字符串时间转换为date对象_js转换日期格式
var s =’2018-10-09 10:23:12′; s = s.replace(/-/g,”/”); var date = new Date(s );
全栈程序员站长
2022/11/09
12.8K0
qt将毫秒级时间戳转换为日期(js把对象变成字符串)
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128759.html原文链接:https://javaforall.cn
全栈程序员站长
2022/07/28
6.8K0
jquery 时间戳转换为日期
1.转换为年月日 new Date(data.createDate).toLocaleDateString()//将json中的时间戳转换为年月日 2.精确到秒 function getMyDate
用户5899361
2020/12/07
4.4K0
Python如何将GrADs常用文件转换为NetCDF格式?
测试数据分享 链接:https://pan.baidu.com/s/1mj1-YpvQN414crNz32f8GA 提取码:wmfr
气象学家
2022/01/18
1.9K0
Python如何将GrADs常用文件转换为NetCDF格式?
javascript中如何正确将日期(Date)字符串转换为日期(Date)对象?
因近日一个项目中要在客户端判断用户输入的日期字符串的大小,所以对日期字符串转日期对象研究了一下,测试代码如下: <script. type="text/javascript"> var sDate1 = "2008/04/02"; var sDate2 = "2005/03/01"; var oDate1 = new Date(sDate1); var oDate2 = new Date(sDate2); if (oDate1 > oDate2)//输出 2008/04/
菩提树下的杨过
2018/01/22
6K0
Javascript日期时间总结(转)
从后台返回的C#时间为:/Date(-62135596800000)/,这个是C#的DateTime.MinValue; 要在html页面展示,一个方法是后端先处理成yyyy-MM-dd HH:mm:ss的格式,前端直接展示。 如果后端不做处理,就需要前端来做处理了,下面就是看前端处理的这种情况。
山河木马
2019/03/05
4.9K0
Javascript日期时间总结(转)
Python如何将GrADs常用文件转换为NetCDF格式?
首先需要确保xgrads库的安装: pip install xgrads Install from github 或者 git clone https://github.com/miniufo/xgrads.git cd xgrads python setup.py install 链接https://github.com/miniufo/xgrads , 有提供示例ctl和dat文件,下面我们是使用的ctl和grd文件转换的,方法类似: #import sys #sys.path.append('/home/gavin/miniconda3/envs/atmpy/lib/python3.8/site-packages') #sys.path from xgrads import CtlDescriptor, open_CtlDataset ds = open_CtlDataset('lst.ctl') ctl = CtlDescriptor(file='lst.ctl') ds.attrs['pdef' ] = 'None' ds.to_netcdf('lst.nc') data = ds.ro1 data.where(data!=ctl.undef).plot(figsize=(9,5), cmap='jet') 以上需要注意两点: 1.如果在jupyter-lab中无法加载xgrads需要手动添加其路径,使用到的是:import sys 2. xgrads存在bug,如果不添加语句ds.attrs['pdef' ] = 'None'会一直报错,无法生成nc文件!
郭好奇同学
2021/08/26
2.9K0
Python如何将GrADs常用文件转换为NetCDF格式?
MySQL时间戳转日期
FROM_UNIXTIME(unix_timestamp,format) 返回表示 Unix 时间标记的一个字符串,根据format字符串格式化。format可以包含与DATE_FORMAT()函数列出的条目同样的修饰符。下列修饰符可以被用在format字符串中: %M 月名字(January……December) %W 星期名字(Sunday……Saturday) %D 有英语前缀的月份的日期(1st, 2nd, 3rd, 等等。) %Y 年, 数字, 4 位 %y 年, 数字, 2 位 %a 缩写的星期名字(Sun……Sat) %d 月份中的天数, 数字(00……31) %e 月份中的天数, 数字(0……31) %m 月, 数字(01……12) %c 月, 数字(1……12) %b 缩写的月份名字(Jan……Dec) %j 一年中的天数(001……366) %H 小时(00……23) %k 小时(0……23) %h 小时(01……12) %I 小时(01……12) %l 小时(1……12) %i 分钟, 数字(00……59) %r 时间,12 小时(hh:mm:ss [AP]M) %T 时间,24 小时(hh:mm:ss) %S 秒(00……59) %s 秒(00……59) %p AM或PM %w 一个星期中的天数(0=Sunday ……6=Saturday ) %U 星期(0……52), 这里星期天是星期的第一天 %u 星期(0……52), 这里星期一是星期的第一天 %% 一个文字“%”。
全栈程序员站长
2022/06/24
6K0
jQuery 将时间戳转换为时间
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>时间戳转换为时间</title> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> </head> <body> <div id="rightalar
王小婷
2021/11/24
2K0
jQuery 将时间戳转换为时间
sql中时间戳转日期
需求: 我将博客和 typecho 后台结合起来,打算做一个在线说说的功能,在 typecho 中输入内容,然后调用接口,实现在我的博客查看说说功能的功能。是不是有点绕?我也这么觉得,但是折腾一下也挺好的。
子舒
2022/06/09
4.5K0
sql中时间戳转日期
如何用python将中文日期转换为数字日期 | 答疑
大家好,这篇文章是在交流群的群友解疑过程中诞生的。 没想到黄同学在帮助群友后还记录了下来,所以就把这篇文章发出来。 问题 他有一个需求,就是对于日期的录入都是中文形式的,需要转换为数字形式的。 由于
朱小五
2020/03/09
3.2K0
Stata | 字符串转日期变量
Stata 将日期、时间以及日期和时间以 1960-01-01 00:00:00.000 为开始时间的整数存储。比如1960-01-01 为 0,1959-12-31 为 -1 , 1960-01-02 为 1 。
PyStaData
2021/03/06
13.3K0
Android 获取时间戳 和时间戳转日期
获取系统时间戳 public String getTime(){ long time=System.currentTimeMillis()/1000;//获取系统时间的10位的时间戳 String str=String.valueOf(time); return str; } 、获取系统时间 long currentTime = System.currentTimeMillis(); SimpleDateFormat formatter = new SimpleDateForma
程思扬
2022/01/10
7.1K0
spring boot 时间戳转日期格式
第一种方式:默认的json处理是 jackson 也就是对configureMessageConverters 没做配置时
全栈程序员站长
2022/06/25
4.6K0
将时间序列转换为分类问题
来源:DeepHub IMBA本文约1900字,建议阅读5分钟在本文中,我们将遵循 CRISP-DM 流程模型,以便我们采用结构化方法来解决业务案例。CRISP-DM 特别适用于潜在分析,通常在行业中用于构建数据科学项目。 本文将以股票交易作为示例。我们用 AI 模型预测股票第二天是涨还是跌。在此背景下,比较了分类算法 XGBoost、随机森林和逻辑分类器。文章的另外一个重点是数据准备。我们必须如何转换数据以便模型可以处理它。 在本文中,我们将遵循 CRISP-DM 流程模型,以便我们采用结构化方法来解决业
数据派THU
2023/05/11
7260
将时间序列转换为分类问题
将tensor转换为图像_tensor转int
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/07
12.5K0
jackson将json转换为json对象
高久峰
2023/07/02
6280
点击加载更多

相似问题

如何使用R将Grib1转换为Netcdf?

31

将日期时间格式从RFC1123转换为日期时间对象

13

将1 20转换为日期时间

13

用R将NetCDF转换为SpatialGridDataFrame

13

SQL:将20071117183011转换为日期/时间(MySQL)

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档