将字符串转换为日期时间 [英] Converting Character String to Datetime

查看:141
本文介绍了将字符串转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据集加载到r中,并将列的类型更改为datetime。

I am trying to load a dataset into r and change the type of a column into datetime.

strptime as.POSIXct as.Date 适用于不同情况;

strptime, as.POSIXct or as.Date for different cases should work;

这是我的代码:

a <- structure(list(DATE = c("01/01/2011 12:00:00", "01/02/2011 12:00:00", 
   "01/03/2011 12:00:00", "01/04/2011 12:00:00", "01/05/2011 12:00:00", 
   "01/06/2011 12:00:00"), VAL = c(65.34447917, 65.23983333, 65.03183333, 
   64.89107292, 64.83333333, 64.848625), id = c("VT1-1", "VT1-1", "VT1-1", 
   "VT1-1", "VT1-1", "VT1-1")), .Names = c("DATE", "VAL", "id"), row.names = c(NA, -6L), 
   class = c("tbl_df", "tbl", "data.frame"))

b1 <- as.POSIXct(a$DATE, format = "%m/%d/%y %H:%M:%S")
b2 <- strptime(a$DATE,"%m/%d/%Y %H:%M/%S")

但他们只是返回 NA 。这很可能是错字。但是在处理不同的日期时间格式时如何避免这种情况?

But they just return NA. It is most probably a typo; but how this can be avoided while dealing with different date-time formats?

推荐答案

R> library(anytime)
R> anytime(a$DATE)
[1] "2011-01-01 12:00:00 CST" "2011-01-02 12:00:00 CST" "2011-01-03 12:00:00 CST"
[4] "2011-01-04 12:00:00 CST" "2011-01-05 12:00:00 CST" "2011-01-06 12:00:00 CST"
R> 

随时创建的软件包使此操作变得简单-您不需要提供格式可能会出错,它只是尝试了一些合理的尝试。对于合理输入,它就可以正常工作

The anytime package was built to make this easy -- you don't need to supply a format you may get wrong, it simply tries a number of plausible ones. For "reasonable" input, it just works.

这篇关于将字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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