使用 R 将时间格式转换为数字
在大多数情况下,我们使用 R 将数字时间转换为 POSIXct 格式。但是,如果我们想比较两个时间点,那么我们更喜欢数字时间格式。例如,我有一个像“2001-03-13 10:31:00”这样的日期格式,
begin <- "2001-03-13 10:31:00"
使用R,我想将其转换为数字(例如,儒略时间),也许类似于1970年- 01-01 00:00:00 和 2001-03-13 10:31:00。
您有什么建议吗?
儒略历始于公元前 45 年(公元 709 年),是尤利乌斯·凯撒对罗马历法的改革。它是在与亚历山大天文学家索西基因协商后选择的,可能是为了近似回归年(至少自喜帕恰斯以来已知)而设计的。请参阅http://en.wikipedia.org/wiki/Julian_calendar
In most cases, we convert numeric time to POSIXct format using R. However, if we want to compare two time points, then we would prefer the numeric time format. For example, I have a date format like "2001-03-13 10:31:00",
begin <- "2001-03-13 10:31:00"
Using R, I want to covert this into a numeric (e.g., the Julian time), perhaps something like the passing seconds between 1970-01-01 00:00:00 and 2001-03-13 10:31:00.
Do you have any suggestions?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只想从字符向量中删除 ":" 、 " " 和 "-" 那么这就足够了:
您应该阅读
?regex
中大约 1/4 的部分字符类。由于“-”在该上下文中作为范围运算符很特殊,因此需要将其放在前面或最后。编辑后,答案显然就是 @joran 写的,除了您需要首先转换为 DateTime 类:
另一点是比较运算符确实适用于 Date 和 DateTime 类变量,因此可能根本不需要转换。这将“开始”与一秒后的时间进行比较,并正确报告开始时间更早:
If you just want to remove ":" , " ", and "-" from a character vector then this will suffice:
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.After your edit then the answer is clearly what @joran wrote, except that you would need first to convert to a DateTime class:
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:
根据修改后的问题,这应该满足您的要求:
结果是一个 unix 时间戳,即自纪元以来的秒数,假设时间戳位于本地时区。
Based on the revised question this should do what you want:
The result is a unix timestamp, the number of seconds since epoch, assuming the timestamp is in the local time zone.
也许这也可以工作:
hms() 会将您的数据从一种时间格式转换为另一种时间格式,这将让您将其转换为秒。请参阅完整的文档。
我尝试这样做是因为我在处理超过 24 小时的格式的数据时遇到了问题。
Maybe this could also work:
hms() will convert your data from one time format into another, this will let you convert it into seconds. See full documentation.
I tried this because i had trouble with data which was in that format but over 24 hours.
?as.POSIX
帮助中的示例给出了这样的结果:
The example from
?as.POSIX
help givesso for you it would be