我需要计算两个数据的两个日期-时间列之间的时间差(分钟/小时/天等),请参阅下面的详细信息。
df1 <- data.frame (Name = c("Aks","Bob","Caty","David"),
timestamp = c("Mon Apr 1 14:23:09 1980", "Sun Jun 12 12:10:21 1975", "Fri Jan 5 18:45:10 1985", "Thu Feb 19 02:26:19 1990"))
df2 <- data.frame (Name = c("Aks","Bob","Caty","David"),
timestamp = c("Apr-01-1980 14:28:00","Jun-12-1975 12:45:10","Jan-05-1985 17:50:30","Feb-19-1990 02:28:00"))I在转换df1 1$时间戳和df1 2$时间戳时面临问题,这里POSIXct & as.Date无法将错误-非数字参数转换为二进制运算符。
我需要计算分钟/小时或天的时间差。
发布于 2021-04-06 13:50:33
一种方法是strptime,并以datetime格式指示适当的指令:
df1$timestamp2 <- strptime(df1$timestamp, "%a %b %d %H:%M:%S %Y")
df2$timestamp2 <- strptime(df2$timestamp, "%b-%d-%Y %H:%M:%S")在这种情况下,你必须:
%a缩短了工作日name%b缩短了month%H小时的月name%d日,24小时的clock%M minute%S second%Y年包括世纪然后可以使用difftime获取差异,并指定单位(在本例中,差异以小时表示):
difftime(df1$timestamp2, df2$timestamp2, units = "hours")输出
Time differences in hours
[1] -0.08083333 -0.58027778 0.91111111 -0.02805556发布于 2021-04-06 13:52:24
如果区域设置妨碍正确阅读,请尝试:
# Store current locale
orig_locale <- Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME", "C")
# Convert to posix-timestamp
df1$timestamp <- as.POSIXct( df1$timestamp, format = "%a %b %d %H:%M:%S %Y")
df2$timestamp <- as.POSIXct( df2$timestamp, format = "%b-%d-%Y %H:%M:%S")
# Restore locale
Sys.setlocale("LC_TIME", orig_locale)
# Calculate difference
df2$timestamp - df1$timestamp
# Time differences in mins
# [1] 4.850000 34.816667 -54.666667 1.683333https://stackoverflow.com/questions/66969180
复制相似问题