r - 从长字符串中提取日期

标签 r date

我有一个数据框,其日期格式如下:

1:9:Tue Aug 12 2014 19:25:24 GMT+0530 (IST)

我想在三个不同的列中提取三个变量日、日期和时间并将其添加到数据框中

Day as Tue
Date as 12/08/2014
Time as 7:25:24PM

前两个数字没有任何意义。

数据框由超过 700,000 行组成,我希望用新列来替换现有列。

最佳答案

将日期时间作为 3 个单独的列添加到 data.frame 时应小心,因为您的 3 列不能唯一标识特定的日期时间,因为您不考虑时区。如果您的所有日期时间都位于同一时区,这应该不是问题。

s <- '1:9:Tue Aug 12 2014 19:25:24 GMT+0530 (IST)'
# If the first two numbers do not mean anything and are always separated by a
# colon, then we can remove them with the following gsub command:
s <- gsub("^[[:digit:]:]+","",s)
# Now we can convert the string to a POSIXlt object, assuming they all follow
# the format of including "GMT" before the signed timezone offset
p <- strptime(s, "%a %b %d %Y %H:%M:%S GMT%z")

即使您的日期时间具有不同的时区偏移,上述内容也将起作用。例如:

# these times are the same, just in a different timezone (the second is made up)
s <- c('1:9:Tue Aug 12 2014 19:25:24 GMT+0530 (IST)',
       '9:1:Tue Aug 12 2014 19:55:24 GMT+0600 (WAT)')
s <- gsub("^[[:digit:]:]+","",s)
p <- strptime(s, "%a %b %d %Y %H:%M:%S GMT%z")
# the times are the same
as.POSIXct(p, tz="UTC")
# [1] "2014-08-12 08:55:24 UTC" "2014-08-12 08:55:24 UTC"

将日期时间格式化为您想要的字符串很容易;只需使用 ?strptime 中的格式规范即可。

data.frame(Day=format(p, "%a"), Date=format(p, "%d/%m/%Y"),
  Time=format(p, "%I:%M:%S%p"), stringsAsFactors=FALSE)

关于r - 从长字符串中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28045865/

相关文章:

r - 如何在 R 中从 2D 矩阵创建 3D 数组?

javascript - 如何从日期数组中获取平均时间?

php - PHP 中的 Cookie 过期日期(在自定义日期)

sql-server - 需要有关 SQL 查询的帮助,从周期表中选择日期范围

r - 给定向量长度的向量到 r 中的数据帧

r - xtable 用于不支持的功能(使用 R)

r - 现在可以将 set.seed 与 Sparklyr 一起使用吗?

r - 基于条件将数据从另一个较小的数据帧添加到数据帧

php - 将 DateTime 转换为 Date Doctrine php

mysql - 请求在sql db中查找时间最接近的元素