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

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

如何在R中将字符转换为时间戳?

在本文中,我们将在 R 编程语言中将字符转换为时间戳。

我们可以使用 strptime() 方法将字符转换为时间戳。 R 语言中的 strptime()函数用于使用给定模板解析给定的日期和时间表示。

语法

strptime(character, format, tz = “”)

在哪里,

  • 字符:以字符串格式给出日期和时间的表示
  • 字符串,指定用于转换的时区

示例 1 :将字符转换为年月日格式时间戳

R
# create character
character = "2021-4-4"
 
# convert character with year month and date format
print(strptime(character, "%Y-%m-%d"))


R
# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
print(strptime(character, "%Y-%m-%d %H:%M:%S"))


R
# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
# and specify time zone as UTC
print(strptime(character, "%Y-%m-%d %H:%M:%S",tz="UTC"))


输出

[1] "2021-04-04 UTC"

示例 2 :将字符转换为时间戳的 R 程序

R

# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
print(strptime(character, "%Y-%m-%d %H:%M:%S"))

输出

[1] "2021-04-04 02:23:34 UTC"

示例 3 :在此示例中,我们将指定时区

R

# create character
character = "2021-4-4 02:23:34"
 
# convert character with year month date
# and Hours minutes and seconds format
# and specify time zone as UTC
print(strptime(character, "%Y-%m-%d %H:%M:%S",tz="UTC"))

输出

[1] "2021-04-04 02:23:34 UTC"