使用 R 将时间格式转换为数字 [英] Converting time format to numeric with R

查看:66
本文介绍了使用 R 将时间格式转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,我们使用 R 将数字时间转换为 posixct 格式.但是,有时,我们想比较哪个时间点更早,那么我们更喜欢数字时间格式.因此,将时间格式转换为数字是一个非常实际的问题.例如,我的数据格式为2001-03-13 10:31:00",

In most cases,we convert numeric time to posixct format using R. However, sometimes, we want to compare which time point is earlier, then we would prefer the numeric time format. Thus, it's quite practical question to convert time format to numeric. For example,I have the data format like "2001-03-13 10:31:00",

  begin <- "2001-03-13 10:31:00"

使用 R,我想弄清楚如何将其转换为数字,例如Julian 时间,类似于 1970-01-01 00:00:00 和 2001-03-13 10:31:00 之间经过的秒数.

Using R, I want to figure out how to covert it into a numeric, e.g. the Julian time, something like the passing seconds between 1970-01-01 00:00:00 and 2001-03-13 10:31:00.

您有什么建议吗?

儒略历开始于公元前 45 年 (709 AUC),是 Julius Caesar 对罗马历法的改革.它是在与亚历山大的天文学家 Sosigenes 协商后选择的,可能旨在近似回归年(至少自喜帕恰斯以来已知).参见 http://en.wikipedia.org/wiki/Julian_calendar

The Julian calendar began in 45 BC (709 AUC) as a reform of the Roman calendar by Julius Caesar. It was chosen after consultation with the astronomer Sosigenes of Alexandria and was probably designed to approximate the tropical year (known at least since Hipparchus). see http://en.wikipedia.org/wiki/Julian_calendar

推荐答案

如果您只是想从字符向量中删除 ":" 、" " 和 "-" 那么这就足够了:

If you jsut want to remove ":" , " ", and "-" from a character vector then this will suffice:

end <- gsub("[: -]", "" , begin, perl=TRUE)
#> end
#[1] "20010313103100"

您应该阅读 ?regex 中关于 字符类 大约 1/4 的部分.由于-"在该上下文中作为范围运算符是特殊的,因此需要将其放在最前面或最后.

You should read the section about 1/4 of the way down in ?regex about character classes. Since the "-" is special in that context as a range operator, it needs to be placed first or last.

在您编辑之后,答案显然是@joran 所写的,只是您需要先转换为 DateTime 类:

After your edit then the answer is clearly what @joran wrote, except that you would need first to convert to a DateTime class:

 as.numeric(as.POSIXct(begin))
#[1] 984497460

要说明的另一点是比较运算符确实适用于 Date 和 DateTime 类变量,因此可能根本不需要转换.这将开始"与一秒后的时间进行比较,并正确报告开始时间更早:

The other point to make is that comparison operators do work for Date and DateTime classed variables so the conversion may not be necessary at all. This compares 'begin' to a time one second later and correctly reports that begin is earlier:

as.POSIXct(begin) < as.POSIXct(begin) +1
 #[1] TRUE

这篇关于使用 R 将时间格式转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆