管理多种日期格式到POSIXct [英] Manage multiple Date formats to POSIXct

查看:45
本文介绍了管理多种日期格式到POSIXct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期格式不同的数据框,第一个是%d/%m/%Y%H:%M:%S",第二个是%Y-%m-%d%H:%M:%S".

I have two dataframe with two different format of date the first is "%d/%m/%Y %H:%M:%S" and the second "%Y-%m-%d %H:%M:%S".

我想创建一个通过指示格式转换为POSIXct的函数.

I want to create a function that convert to POSIXct by indicating the format.

我的代码:

date_func <- function(df){
 colnum <- grep("DATE", colnames(df))
 df[, (colnum) := lapply(.SD, dmy_hms), .SDcols = colnum]
 return(df)
}

对于第一种格式,它可以工作,但是对于第二种格式,转换后我只有NA值.

For the first format it's works but for the second I have only NA values after the conversion.

那么,如何创建一个可以将POSIXct转换为指定格式的函数?

So, how can I create a function that convert to POSIXct whatever the indicated format?

感谢您的帮助.

推荐答案

lubridate 提供了很好的选择来处理异构格式的日期/时间.可以使用 parse_date_time .一个简单的示例,将日期/时间转换为OP中指定的格式:

Package lubridate provides very good option to handle date/time in heterogeneous format. The parse_date_time can be used. A simple example on converting date/time in format specified in OP are:

library(lubridate)
>parse_date_time(c("01/12/2016 01:11:54", "2015-12-31 10:05:11"), c("dmY HMS", "Ymd HMS"))
# [1] "2016-12-01 01:11:54 UTC" "2015-12-31 10:05:11 UTC"

这篇关于管理多种日期格式到POSIXct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆