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

时间:2022-01-19 15:45:14

Consider a string in the format

考虑格式的字符串

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

My goal is to convert those strings to POSIXct format 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.POSIXct seems 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”。这是我的问题吗?

1 个解决方案

#1


17  

You need to specify a format for your conversion. Take a read of ?strptime to 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"

#1


17  

You need to specify a format for your conversion. Take a read of ?strptime to 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"