簡體   English   中英

從字符串獲取月,日和小時

[英]Get month, day and hour from string

我有一個日期格式為2014-06-10 06:12:35 BRT的數據框,我將比較日期以查看它們是否屬於同一社交日(每天凌晨3:00至3:00) )。 但是當我嘗試僅選擇日期

format(as.Date(df$x,format="%Y-%m-%dT%H:%M:%SZ"), "%d"),

有時他會加1,例如2014-06-13 22:54:36 BRT它顯示14

如果我想花時間

format(as.Date(df$x,format="%Y-%m-%dT%H:%M:%SZ"), "%H") 

它總是顯示為00

我應該如何處理R中的日期?

在R中,時間使用POSIXctPOSIXlt類,日期使用Date類。

日期存儲為自1970年1月1日以來的天數,時間存儲為自1970年1月1日以來的秒數。

因此,例如:

d <- as.Date("1971-01-01")
unclass(d)  # one year after 1970-01-01
# [1] 365

pct <- Sys.time()  # in POSIXct
unclass(pct)  # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt)  # up is now a list containing the components of time
names(up)
# [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"  
# [11] "gmtoff"
up$hour
# [1] 9

要對日期和時間執行操作:

plt - as.POSIXlt(d)
# Time difference of 16420.61 days

要處理日期,可以使用strptime() (從手冊頁中借用這些示例):

strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"

# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"

要處理您的特定日期:

dateString <- "2014-06-10 06:12:35"
d <- strptime(dateString, "%Y-%m-%d %H:%M:%S")

注意: 我在R區域列表中找不到“ BRT”時區,因此我的上述時間設置為EDT時區:

"BRT" %in% OlsonNames()
# [1] FALSE

暫無
暫無

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

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