我有一个数据框,其日期格式如下:
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/