简体   繁体   English

R 时间格式转换

[英]R time format conversion

I have almost finished my script but I have a problem with my dates format.我几乎完成了我的剧本,但我的日期格式有问题。 I installed lubridate package used the as_date function, but it doesn't give me what I want (a date).我安装了 lubridate package 使用 as_date function,但它没有给我我想要的(日期)。 "time" is my variable, I put its description below. “时间”是我的变量,我把它的描述放在下面。

I do not put my entire script since the concern is only about this format question (and it implies a huge.netcdf file impossible to download)我没有把我的整个脚本放在一起,因为只关心这个格式问题(这意味着一个巨大的 .netcdf 文件无法下载)

Could you help me please?请问你能帮帮我吗?

class(time)
[1] "array"

head(time)
[1] 3573763200 3573774000 3573784800 3573795600 3573806400 3573817200

tunits
$long_name
[1] "time in seconds (UT)"
$standard_name
[1] "time"
$units
[1] "seconds since 1900-01-01T00:00:00Z"
$axis
[1] "T"
$time_origin
[1] "01-JAN-1900 00:00:00"
$conventions
[1] "relative number of seconds with no decimal part"

#conversion
date = as_date(time,tz="UTC",origin = "1900-01-01")
head(date)
[1] "-5877641-06-23" "-5877641-06-23" "-5877641-06-23" "-5877641-06-23"
[5] "-5877641-06-23" "-5877641-06-23"

as_date() calculates the date using the number of days since the origin. as_date()使用自原点以来的天数计算日期。

What you are looking for seems to be as_datetime() also from the lubridate package which calculates the date using the number of seconds since the origin.您正在寻找的似乎也是来自lubridate包的as_datetime() ,它使用自原点以来的秒数计算日期。 In your example this would be:在您的示例中,这将是:

time <- c(3573763200,3573774000,3573784800,3573795600,3573806400,3573817200)
date <- as_datetime(time, tz = "UTC", origin = "1900-01-01") %>% date()

Using a dplyr pipe and the date() function from lubridate to extract the date from the as_datetime() function.使用dplyr管和date()从函数lubridate取出从日期as_datetime()函数。

Time is in seconds since 01/01/1900.时间以 1900 年 1 月 1 日以来的秒为单位。 Converting a value in time to an actual date would work as follows, using the seconds methods in lubridate :time值转换为实际日期的工作方式如下,使用lubridateseconds方法:

lubridate::ymd("1900-01-01") + lubridate::seconds(3573763200)

You can vectorize it:您可以将其矢量化:

lubridate::ymd("1900-01-01") + lubridate::seconds(time)
date <- as_date(time/(24*60*60), tz = "UTC", origin = "1900-01-01") date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM