字符向量转换为时间

字符向量转换为时间

本文介绍了将字符向量转换为时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下字符向量转换为时间变量.

I want to convert the following character vector into a time variable.

times <-
  c(
    "9/9/2015 16:03:13", "9/9/2015 17:03:13", "9/9/2015 17:56:38",
    "9/9/2015 17:57:29", "9/9/2015 19:52:55", "9/10/2015 8:18:47",
    "9/9/2015 15:47:56", "9/9/2015 22:23:56", "9/10/2015 0:07:41",
    "9/10/2015 11:46:23", "9/11/2015 10:12:21", "9/11/2015 15:33:41",
    "9/12/2015 9:08:46", "9/15/2015 12:54:51", "9/15/2015 12:55:40",
    "9/15/2015 14:45:39", "9/15/2015 14:58:01", "9/15/2015 20:42:41",
    "9/16/2015 8:16:15", "9/16/2015 12:55:40", "9/16/2015 15:34:39",
    "9/17/2015 13:34:14", "9/17/2015 16:15:00"
  )

我尝试了以下操作:

fasttime::fastPOSIXct(format(times))

但是我有很多 NAs :

structure(c(1425830593, 1425834193, 1425837398, 1425837449, 1425844375, 
           1428394727, 1425829676, 1425853436, 1428365261, 1428407183, 1431079941, 
           1431099221, 1433668126, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
), class = c("POSIXct", "POSIXt"))    

推荐答案

这里有2个选项:

使用base-R:

as.POSIXct(times,format="%m/%d/%Y %H:%M:%S") ## this uses internally strptime

或使用方便的 lubridate 包:

library(lubridate)
parse_date_time(times,"mdYHMS")

library(lubridate)
mdy_hms(times)

fastPOSIXct 是一个很好的选择,但我认为它不能在这里使用(它假定数据具有某种格式).

fastPOSIXct is an excellent option but I don't think it can be used here ( it asumes that the data have a certain format).

这篇关于将字符向量转换为时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 00:49