保持日期和时间格式一致

时间:2019-05-29 22:02:31

标签: r date time

我有一些日期和时间,由于某种原因,在新月初时会在格式之间进行切换。我想将它们分别转换为日,月,年(19年而不是2019年)和24小时制(秒)。我已经成功地使用strptime切换了一半,但不适用于整个数据集。

这里是一个例子:

datetime <- c("02/28/19 11:39:00 PM", "02/28/19 11:40:00 PM", "02/28/19 11:41:00 PM", 
"02/28/19 11:42:00 PM", "02/28/19 11:43:00 PM", "02/28/19 11:44:00 PM", 
"02/28/19 11:45:00 PM", "02/28/19 11:46:00 PM", "02/28/19 11:47:00 PM", 
"02/28/19 11:48:00 PM", "02/28/19 11:49:00 PM", "02/28/19 11:50:00 PM", 
"02/28/19 11:51:00 PM", "02/28/19 11:52:00 PM", "02/28/19 11:53:00 PM", 
"02/28/19 11:54:00 PM", "02/28/19 11:55:00 PM", "02/28/19 11:56:00 PM", 
"02/28/19 11:57:00 PM", "02/28/19 11:58:00 PM", "02/28/19 11:59:00 PM", 
"03/01/2019 00:00", "03/01/2019 00:01", "03/01/2019 00:02", "03/01/2019 00:03", 
"03/01/2019 00:04", "03/01/2019 00:05", "03/01/2019 00:06", "03/01/2019 00:07", 
"03/01/2019 00:08", "03/01/2019 00:09", "03/01/2019 00:10", "03/01/2019 00:11", 
"03/01/2019 00:12", "03/01/2019 00:13", "03/01/2019 00:14", "03/01/2019 00:15", 
"03/01/2019 00:16", "03/01/2019 00:17", "03/01/2019 00:18", "03/01/2019 00:19", 
"03/01/2019 00:20", "03/01/2019 00:21", "03/01/2019 00:22", "03/01/2019 00:23", 
"03/01/2019 00:24", "03/01/2019 00:25", "03/01/2019 00:26", "03/01/2019 00:27", 
"03/01/2019 00:28", "03/01/2019 00:29")

1 个答案:

答案 0 :(得分:1)

一种可能的方法是

lubridate::mdy_hms(datetime, truncated = 1L)

返回

 [1] "2019-02-28 23:39:00 UTC" "2019-02-28 23:40:00 UTC" "2019-02-28 23:41:00 UTC" "2019-02-28 23:42:00 UTC"
 [5] "2019-02-28 23:43:00 UTC" "2019-02-28 23:44:00 UTC" "2019-02-28 23:45:00 UTC" "2019-02-28 23:46:00 UTC"
 [9] "2019-02-28 23:47:00 UTC" "2019-02-28 23:48:00 UTC" "2019-02-28 23:49:00 UTC" "2019-02-28 23:50:00 UTC"
[13] "2019-02-28 23:51:00 UTC" "2019-02-28 23:52:00 UTC" "2019-02-28 23:53:00 UTC" "2019-02-28 23:54:00 UTC"
[17] "2019-02-28 23:55:00 UTC" "2019-02-28 23:56:00 UTC" "2019-02-28 23:57:00 UTC" "2019-02-28 23:58:00 UTC"
[21] "2019-02-28 23:59:00 UTC" "2019-03-01 00:00:00 UTC" "2019-03-01 00:01:00 UTC" "2019-03-01 00:02:00 UTC"
[25] "2019-03-01 00:03:00 UTC" "2019-03-01 00:04:00 UTC" "2019-03-01 00:05:00 UTC" "2019-03-01 00:06:00 UTC"
[29] "2019-03-01 00:07:00 UTC" "2019-03-01 00:08:00 UTC" "2019-03-01 00:09:00 UTC" "2019-03-01 00:10:00 UTC"
[33] "2019-03-01 00:11:00 UTC" "2019-03-01 00:12:00 UTC" "2019-03-01 00:13:00 UTC" "2019-03-01 00:14:00 UTC"
[37] "2019-03-01 00:15:00 UTC" "2019-03-01 00:16:00 UTC" "2019-03-01 00:17:00 UTC" "2019-03-01 00:18:00 UTC"
[41] "2019-03-01 00:19:00 UTC" "2019-03-01 00:20:00 UTC" "2019-03-01 00:21:00 UTC" "2019-03-01 00:22:00 UTC"
[45] "2019-03-01 00:23:00 UTC" "2019-03-01 00:24:00 UTC" "2019-03-01 00:25:00 UTC" "2019-03-01 00:26:00 UTC"
[49] "2019-03-01 00:27:00 UTC" "2019-03-01 00:28:00 UTC" "2019-03-01 00:29:00 UTC"

对于给定的样本数据集。