【问题标题】:Extract two combined dates and times from a string从字符串中提取两个组合的日期和时间
【发布时间】:2017-09-02 17:57:30
【问题描述】:

请告诉我如何从 ("2015-08-11 03:14:00 UTC--2015-08-11 04:14:00 UTC") 中提取日期和时间。请注意,此字符串包含具有两个日期和两个时间的时间间隔。我想将其分解为 4 个单独的字符串,例如 Date 1、Time 1、Date 2、Time 2,然后将它们存储在 4 个单独的向量中。

谢谢。

【问题讨论】:

  • 在 R 中,时间对象必须有一个与之关联的日期。为了进一步分析,我建议将时间部分与日期一起保存,并将结果存储为 POSIXct 对象。
  • 现在我有“2015-08-10 07:14:00 UTC”作为 Chr,我使用了以下内容,但我得到了 NA。 data$datetime = as.POSIXct(data$datetime, format = '%m/%d/%Y %H:%M').
  • 现在有效:as.POSIXct(data$datetime, format = '%Y-%m-%d %H:%M:%S')

标签: r


【解决方案1】:

试试下面的。

x <- "2015-08-11 03:14:00 UTC--2015-08-11 04:14:00 UTC"
y <- strsplit(x, "--")[[1]]

dates <- as.Date(y)
times <- strftime(y, format = "%H:%M:%S")

【讨论】:

    【解决方案2】:

    您从未提及是否需要输入字符串中的功能日期和时间。如果您需要简单地解析时间戳的每个部分,那么使用gsub 是一种选择。

    x <- "2015-08-11 03:14:00 UTC--2015-08-11 04:14:00 UTC"
    y <- unlist(strsplit(x, "--"))
    dates <- sapply(y, function(x) gsub("(\\d{4}-\\d{2}-\\d{2}).*", "\\1", x))
    times <- sapply(y, function(x) gsub(".*(\\d{2}:\\d{2}:\\d{2}.*)", "\\1", x))
    dates
    [1] "2015-08-11" "2015-08-11"
    times
    [1] "03:14:00 UTC" "04:14:00 UTC"
    

    演示在这里:

    Rextester

    【讨论】:

    • 谢谢。我还找到了一种更简单的方法:我们可以定义一个字符串并使用 substr(str1,...,...)。
    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2011-03-31
    • 1970-01-01
    • 2023-01-04
    • 2021-01-05
    • 2013-06-14
    • 2019-03-31
    • 1970-01-01
    相关资源
    最近更新 更多