📌  相关文章
📜  如何在 R 中将字符串转换为日期时间?

📅  最后修改于: 2022-05-13 01:54:40.006000             🧑  作者: Mango

如何在 R 中将字符串转换为日期时间?

在本文中,我们将讨论如何在 R 编程语言中将字符串转换为日期时间。我们可以使用 POSIXct函数将字符串转换为 DateTime

示例 1:将一个字符串转换为日期时间

在这里,我们将一个字符串作为输入并将其转换为 DateTime。

R
# consider a string
string = "2021-11-21 4:5:23"
 
# convert string to datetime
final = as.POSIXct(string, format="%Y-%m-%d %H:%M:%S", tz="UTC")
 
# display
print(final)
 
# get the type
class(final)


R
# consider a dataframe
dataframe = data.frame(data = c( "2021-11-21 4:5:23",
                                "2021-11-22 4:5:23",
                                "2021-11-23 4:5:23",
                                "2021-11-24 4:5:23",
                                "2021-11-25 4:5:23"))
 
# convert data column  to datetime
print(as.POSIXct(dataframe$data,
                 format="%Y-%m-%d %H:%M:%S",
                 tz="UTC"))


输出:

[1] "2021-11-21 04:05:23 UTC"
[1] "POSIXct" "POSIXt" 

示例 2:将字符串列转换为日期时间

在这里,我们从数据框中获取一个字符串,然后转换为 DateTime

R

# consider a dataframe
dataframe = data.frame(data = c( "2021-11-21 4:5:23",
                                "2021-11-22 4:5:23",
                                "2021-11-23 4:5:23",
                                "2021-11-24 4:5:23",
                                "2021-11-25 4:5:23"))
 
# convert data column  to datetime
print(as.POSIXct(dataframe$data,
                 format="%Y-%m-%d %H:%M:%S",
                 tz="UTC"))

输出:

[1] "2021-11-21 04:05:23 UTC" "2021-11-22 04:05:23 UTC"
[3] "2021-11-23 04:05:23 UTC" "2021-11-24 04:05:23 UTC"
[5] "2021-11-25 04:05:23 UTC"