从DateTime向量获取小时 [英] obtain hour from DateTime vector

查看:58
本文介绍了从DateTime向量获取小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在data.frame中有一个DateTime向量,其中数据帧由8760个观测值组成,这些观测值表示全年的小时间隔,例如

I have a DateTime vector within a data.frame where the data frame is made up of 8760 observations representing hourly intervals throughout the year e.g.

2010-01-01 00:00
2010-01-01 01:00
2010-01-01 02:00
2010-01-01 03:00

等。

我想创建一个具有原始DateTime向量作为第一列的data.frame,然后在第二列中创建小时值,例如

I would like to create a data.frame which has the original DateTime vector as the first column and then the hourly values in the second column e.g.

2010-01-01 00:00          00:00
2010-01-01 01:00          01:00

如何实现?

推荐答案

使用格式 strptime 提取时间信息。

创建POSIXct向量:

Create a POSIXct vector:

x <- seq(as.POSIXct("2012-05-21"), by=("+1 hour"), length.out=5)

提取时间:

data.frame(
  date=x,
  time=format(x, "%H:%M")
)

                 date  time
1 2012-05-21 00:00:00 00:00
2 2012-05-21 01:00:00 01:00
3 2012-05-21 02:00:00 02:00
4 2012-05-21 03:00:00 03:00
5 2012-05-21 04:00:00 04:00






如果输入向量是字符向量,则必须首先转换为POSIXct:


If the input vector is a character vector, then you have to convert to POSIXct first:

创建一些数据

dat <- data.frame(
  DateTime=format(seq(as.POSIXct("2012-05-21"), by=("+1 hour"), length.out=5), format="%Y-%m-%d %H:%M")
)
dat
          DateTime
1 2012-05-21 00:00
2 2012-05-21 01:00
3 2012-05-21 02:00
4 2012-05-21 03:00
5 2012-05-21 04:00

拆分时间:

data.frame(
  DateTime=dat$DateTime,
  time=format(as.POSIXct(dat$DateTime, format="%Y-%m-%d %H:%M"), format="%H:%M")
)

          DateTime  time
1 2012-05-21 00:00 00:00
2 2012-05-21 01:00 01:00
3 2012-05-21 02:00 02:00
4 2012-05-21 03:00 03:00
5 2012-05-21 04:00 04:00

这篇关于从DateTime向量获取小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆