R语言 如何把日期转换为数字
在这篇文章中,我们将讨论如何在R编程语言中把日期转换成数字。
方法1:使用as.numeric()
这个函数用于将日期转换成数字
语法:
as.numeric(date)
其中日期为输入日期。
例子 :
data = as.POSIXct("1/1/2021 1:05:00 AM",
format="%m/%d/%Y %H:%M:%S %p")
# display
print(data)
# convert to numeric
print(as.numeric(data))
输出:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
如果我们想从这个数字中得到天数,就用这个数字除以86400。
as.numeric(date)/86400
如果我们想得到从日期开始的年数,那么就用它除以365。
as.numeric(date)/86400/365
示例 :R程序将日期转换为天和年
data = as.POSIXct("1/1/2021 1:05:00 AM",
format="%m/%d/%Y %H:%M:%S %p")
# display
print(data)
# convert to numeric
print(as.numeric(data))
# convert to numeric and get days
print(as.numeric(data)/86400)
# convert to numeric and get years
print((as.numeric(data)/86400)/365)
输出:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
[1] 18628.05
[1] 51.03574
方法2:使用lubridate包的函数
在这里,通过使用这个模块,我们可以分别获得日、月、年、时、分、秒的整数格式。
语法:
day :
day(date)
month :
month(date)
year :
year(date)
hour :
hour(date)
minute :
minute(date)
second :
second(date)
例子 :
# load the library
library("lubridate")
# create date
data = as.POSIXct("1/1/2021 1:05:00 AM",
format="%m/%d/%Y %H:%M:%S %p")
# display
print(data)
# get the day
print(day(data))
# get the month
print(month(data))
# get the year
print(year(data))
# get the hour
print(hour(data))
# get the minute
print(minute(data))
# get the second
print(second(data))
输出:
[1] "2021-01-01 01:05:00 UTC"
[1] 1
[1] 1
[1] 2021
[1] 1
[1] 5
[1] 0