R中的时间戳转换和计算不同DFs的两列之间的时间差
我需要计算两个数据帧的两个日期时间列之间的时间差(以分钟/小时/天等为单位),请查看下面的详细信息R中的时间戳转换和计算不同DFs的两列之间的时间差,r,timestamp,R,Timestamp,我需要计算两个数据帧的两个日期时间列之间的时间差(以分钟/小时/天等为单位),请查看下面的详细信息 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
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"))
df1一种方法是strtime
并以日期时间格式指示适当的指令:
df1$timestamp2 <- strptime(df1$timestamp, "%a %b %d %H:%M:%S %Y")
df2$timestamp2 <- strptime(df2$timestamp, "%b-%d-%Y %H:%M:%S")
输出
Time differences in hours
[1] -0.08083333 -0.58027778 0.91111111 -0.02805556
一种方法是strtime
,并以datetime格式指示适当的指令:
df1$timestamp2 <- strptime(df1$timestamp, "%a %b %d %H:%M:%S %Y")
df2$timestamp2 <- strptime(df2$timestamp, "%b-%d-%Y %H:%M:%S")
输出
Time differences in hours
[1] -0.08083333 -0.58027778 0.91111111 -0.02805556
如果区域设置阻止正确读取,请尝试:
# 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.683333
#存储当前区域设置
原始语言环境如果语言环境设置阻止正确读取,请尝试:
# 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.683333
#存储当前区域设置
orig_locale也使用anydate,但它只是将其转换为properdate减去timestamp使用anydate,但它只是将其转换为properdate减去timestamp