如何从 R 中的日期时间中提取时间?
在本文中,我们将使用 lubridate()函数和 format()函数从 R 编程语言中的 Datetime 中提取时间。
注:日期时间为时间日期格式(YYYY/MM/DD HH:MM:SS)即年:月:日 小时:分:秒
在哪里,
- 年:月:日在日期之下
- 小时:分钟:秒来计时
方法一:使用format()函数
我们将只提取时间并为此创建一个变量并为其分配一个时间戳。然后,从时间戳中提取时间。我们可以通过使用 as.POSIXct()函数来做到这一点。要获得特定的时间小时格式,我们可以使用 format()函数
Syntax:
format(as.POSIXct(data), format = “%H:%M”)
Parameter:
- as.POSIXct() is used to extract time from the time stamp
- format is used to get the time format. Ex : hours:Minutes and seconds
- format = “%H:%M:%S” (To get hours: minutes :seconds)
- format = “%H:%M” (To get hours: minutes )
- format = “%H” (To get hours)
- data is the time stamp
示例 1:
R
# 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")))
R
# 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")))
R
# 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)
输出:
示例 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")))
输出:
方法二:使用lubridate()函数
lubridate() 包用于从日期时间单独返回时间。它将分别返回小时、分钟和秒。
- 要从日期时间获取小时,我们将使用 hour 命令
句法:
hour(datetime)
Returns the time in hours
- 要从日期时间获取分钟,我们将使用 minute 命令
句法:
minute(datetime)
Returns the time in minutes
- 要从日期时间获取秒数,我们将使用第二个命令
句法:
second(datetime)
Returns the time in seconds
示例 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)
输出: