R语言 如何从日期时间中提取时间

R语言 如何从日期时间中提取时间

在这篇文章中,我们将使用lubridate()函数和format()函数在R编程语言中从Datetime中提取时间。

注意: 数据时间的格式是时间和日期(YYYY/MM/DD HH:MM:SS),即:年:月:日 小时:分钟:秒

其中。

  • 年:月:日是在日期下
  • 时间下有小时:分钟:秒。

方法1:使用format()函数

我们将只提取时间,为此创建一个变量并给它分配一个时间戳。然后,从时间戳中提取时间。我们可以通过使用as.POSIXct()函数来做到这一点。要获得一个特定的时间小时格式,我们可以使用format()函数

语法

format(as.POSIXct(data), format = “%H:%M”)

参数

  • as.POSIXct()用于从时间戳中提取时间
  • format用于获取时间格式。例如:小时:分钟和秒
    • format = “%H:%M:%S” (获取小时:分钟:秒)
    • format = “%H:%M” (获得小时:分钟)
    • format = “%H” (获取小时数)
  • 数据是时间戳

例1 :

# create variable with one time stamp 
data ="2021/05/25 12:34:25"
                             
# get time from date using format in the 
# form of hours
print(paste(
  "Hours : ", format(as.POSIXct(data), format = "%H")))
  
# get time from date using format in the 
# form of minutes
print(paste(
  "Minutes : ", format(as.POSIXct(data), format = "%M")))
  
# get time from date using format in the 
# form of seconds
print(paste(
  "Seconds : ", format(as.POSIXct(data), format = "%S")))
  
# get time from date using format in the 
# form of minutes
print(paste(
  "Hours and Minutes : ", format(as.POSIXct(data), format = "%H:%M")))
  
# get time from date using format in the 
# form of seconds
print(paste(
  "Time : ", format(as.POSIXct(data), format = "%H:%M:%S")))
Bash

输出

如何在R语言中从日期时间中提取时间?

例2 :

# create vector that stores five time stamps
data =c("2021/05/25 12:34:25","2022/05/25 11:39:25",
        "2011/05/25 08:31:25","2013/04/13 1:34:25",
        "2018/05/25 12:34:25")
                             
# get time from date using format in the
# form of seconds
print(paste("Time : ", format(
  as.POSIXct(data), format = "%H:%M:%S")))
Bash

输出

如何在R语言中从日期时间中提取时间?

方法2:使用lubridate()函数

lubridate()包用于从日期时间中单独返回时间。它将分别返回小时、分钟和秒。

  • 为了从日期时间中获得小时,我们将使用小时命令

语法

hour(datetime)

返回以小时为单位的时间

  • 要从日期时间中获取分钟,我们将使用 minute 命令

语法

minute(datetime)

返回以分钟为单位的时间

  • 要从日期时间中获取秒,我们将使用second命令

语法

second(datetime)

返回以秒为单位的时间

例1 :

# load the package
library('lubridate')
  
# datetime variable
data ="2021/05/25 12:34:25"
  
# extract hour
hour(data)
  
# extract minute
minute(data)
  
# extract the second
second(data)
Bash

输出

如何在R语言中从日期时间中提取时间?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册