在R中将特定格式字符串转为时间戳时遇输入过长报错的解决方法
问题:strptime转换时间字符串时报错“input string is too long”
问题场景
给定格式为Tue Feb 11 12:28:36 +0000 2014的时间字符串,尝试用R语言的strptime函数转换为时间戳,执行代码如下:
timeobj <- strptime(df[1], format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT")
其中df[1]指向上述格式的字符串列,但运行后抛出错误:
Error in strptime(df[1], format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT") : input string is too long
数据框前5条数据的dput结果如下:
dput(df[1:5, 1]) = c("Tue Feb 11 12:47:26 +0000 2014", "Tue Feb 11 12:55:09 +0000 2014", "Tue Feb 11 13:22:29 +0000 2014", "Tue Feb 11 13:24:31 +0000 2014", "Tue Feb 11 13:34:00 +0000 2014")
问题原因
报错的核心是索引方式错误:df[1]返回的是一个完整的数据框(data.frame)对象,而strptime需要的是单纯的字符向量。当数据框被传入strptime时,会被强制转换为字符串形式(比如"data.frame with 5 rows and 1 columns..."),这个转换后的字符串长度远超过实际时间字符串,因此触发“输入字符串过长”的错误。
解决方法
只需修改索引方式,把df[1]替换为以下任意一种即可:
- 用双层方括号提取列的字符向量:
timeobj <- strptime(df[[1]], format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT")
- 用逗号索引提取列:
timeobj <- strptime(df[,1], format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT")
- 如果列有明确名称,直接用列名提取(更直观):
# 假设列名为time_str timeobj <- strptime(df$time_str, format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT")
验证测试
用你提供的测试数据验证:
test_df <- data.frame(time_str = c("Tue Feb 11 12:47:26 +0000 2014", "Tue Feb 11 12:55:09 +0000 2014", "Tue Feb 11 13:22:29 +0000 2014", "Tue Feb 11 13:24:31 +0000 2014", "Tue Feb 11 13:34:00 +0000 2014")) strptime(test_df[[1]], format = "%a %b %e %H:%M:%S %z %Y", tz = "GMT")
执行后会正确返回POSIXlt类型的时间对象:
[1] "2014-02-11 12:47:26 GMT" "2014-02-11 12:55:09 GMT" "2014-02-11 13:22:29 GMT" "2014-02-11 13:24:31 GMT" "2014-02-11 13:34:00 GMT"
内容的提问来源于stack exchange,提问作者yuyu
相关产品推荐
相关产品推荐

