【问题标题】:Get month, day and hour from string从字符串中获取月、日和小时
【发布时间】:2023-03-16 20:50:02
【问题描述】:

我有一个日期格式为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 中的日期?

【问题讨论】:

  • 您的format"2014-06-13 22:54:36 BRT" 不匹配。请修复。
  • 您被时区差异所震惊 - 与此处相同的问题:stackoverflow.com/questions/17098862/… 确保 tz= 匹配 as.Date
  • 尝试例如as.Date(as.POSIXct("2014-06-13 22:54:36", tz="Brazil/East"), tz="Brazil/East")并与as.Date(as.POSIXct("2014-06-13 22:54:36", tz="Brazil/East"))比较

标签: r date datetime


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多