簡體   English   中英

R 中的時間戳轉換和計算不同 DF 的 2 列之間的時間差

[英]Timestamp conversion in R and calculating Time Difference between 2 Columns of different DFs

我需要計算兩個數據幀的 2 個日期時間列之間的分鍾/小時/天等時間差,請在下面找到詳細信息

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$timestamp 和 df2$timestamp 時遇到問題,這里 POSIXct & as.Date 無法正常工作,出現錯誤 - 二進制運算符的非數字參數

我需要以分鍾/小時或天為單位計算時間差異

一種方法是strptime並以日期時間格式指示適當的指令:

df1$timestamp2 <- strptime(df1$timestamp, "%a %b %d %H:%M:%S %Y")
df2$timestamp2 <- strptime(df2$timestamp, "%b-%d-%Y %H:%M:%S")

在這種情況下,您有:

  • %a縮寫的工作日名稱
  • %b縮寫月份名稱
  • 一個月中的%d
  • %H小時,24 小時制
  • %M分鍾
  • %S
  • %Y年包括世紀

然后您可以使用difftime來獲取差異,並指定單位(在這種情況下,差異以小時表示):

difftime(df1$timestamp2, df2$timestamp2, units = "hours")

Output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM