string 将日期时间字符串转换为 R 中的 POSIXct 日期/时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21667212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:13:36  来源:igfitidea点击:

converting datetime string to POSIXct date/time format in R

stringrdatetimeposixct

提问by CFrench

Consider a string in the format

考虑格式中的字符串

test <- "YYYY-MM-DDT00:00:00.000-08:00"

My goal is to convert those strings to POSIXctformat so that I can plot the data. my initial thought was to use

我的目标是将这些字符串转换为POSIXct格式,以便我可以绘制数据。我最初的想法是使用

as.POSIXct(test)

...but that seems to truncate the datetime to just date. Any thoughts? The help info for as.POSIXctseems to imply that the input should be date and time separated by a space, not by a "T". Is this my issue?

...但这似乎将日期时间截断为日期。有什么想法吗?的帮助信息as.POSIXct似乎暗示输入应该是由空格分隔的日期和时间,而不是由“T”分隔。这是我的问题吗?

回答by thelatemail

You need to specify a format for your conversion. Take a read of ?strptimeto see all of the options for date formats.

您需要为转换指定格式。阅读?strptime以查看日期格式的所有选项。

#YYYY-MM-DDT00:00:00.000-08:00
test <- "2013-12-25T04:32:16.500-08:00"
z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS")
op <- options(digits.secs = 3)
z
#[1] "2013-12-25 04:32:16.5 EST"