问题描述
我有一个包含日期时间字符列的数据框.
I have a data frame with a character column of date-times.
当我使用 as.Date
时,我的大部分字符串都被正确解析,除了少数实例.下面的示例有望向您展示正在发生的事情.
When I use as.Date
, most of my strings are parsed correctly, except for a few instances. The example below will hopefully show you what is going on.
# my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
str_locate(prods.all$Date, " ")[1]-1),
"%m/%d/%Y")
# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
# Date Date2
# 1925 10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15
如您所见,某些日期的年份不准确.该模式似乎发生在当天两位数时.
As you can see, the year of some of the dates is inaccurate. The pattern seems to occur when the day is double digit.
如果您能提供任何帮助,我们将不胜感激.
Any help you can provide will be greatly appreciated.
推荐答案
你可能把事情想得太复杂了,你有什么理由需要 stringr 包吗?您可以使用 as.Date
及其 format
参数来指定字符串的输入格式.
You may be overcomplicating things, is there any reason you need the stringr package? You can use as.Date
and its format
argument to specify the input format of your string.
df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
as.Date(df$Date, format = "%m/%d/%Y %H:%M:%S")
# [1] "2009-10-09" "2009-10-15"
注意?as.Date
的Details部分:
根据指定格式的需要处理字符串:忽略任何尾随字符
因此,这也有效:
as.Date(df$Date, format = "%m/%d/%Y)
# [1] "2009-10-09" "2009-10-15"
可用于指定输入format
的所有转换规范都可以在?strptime
的Details 部分中找到.确保转换规范的顺序以及任何分隔符与输入字符串的格式完全一致.
All the conversion specifications that can be used to specify the input format
are found in the Details section in ?strptime
. Make sure that the order of the conversion specification as well as any separators correspond exactly with the format of your input string.
更一般地,如果您还需要时间组件,请使用 as.POSIXct
或 strptime
:
More generally and if you need the time component as well, use as.POSIXct
or strptime
:
as.POSIXct(df$Date, "%m/%d/%Y %H:%M:%S")
strptime(df$Date, "%m/%d/%Y %H:%M:%S")
我在猜测您提供的部分结果可能会显示您的实际数据.
I'm guessing at what your actual data might look at from the partial results you give.
这篇关于将日期时间字符串转换为类 Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!