将日期时间字符串解析为Date类的最快方法 [英] Fastest way to parse a date-time string to class Date

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

问题描述

我有一列以日期为字符的列,格式为 10/17/2017 12:00:00 AM .我想解析字符串并仅将日期部分保留为类 Date ,即 2017-10-17 .我正在使用-

I have a column with dates as character in the format 10/17/2017 12:00:00 AM. I want parse the string and keep only the date part as class Date, i.e. 2017-10-17. I am using -

df$ReportDate = as.Date(df$ReportDate, format = "%m/%d/%Y %I:%M:%S %p") 
df$ReportDate = as.Date(format(df$ReportDate, "%Y-%m-%d"))

这行得通,但是数据帧有超过500万行,因此大约需要2分钟.

this works, but the dataframe has over 5 million rows so this takes close to two mins.

  user  system elapsed 
104.73    0.55  105.46 

是否有更快,更有效的方法来做到这一点?

Is there a faster and more efficient way to do this?

推荐答案

请注意,日期后 as.Date 会忽略垃圾,因此在我使用的不是特别快的笔记本电脑上,此时间不到10秒:/p>

Note that as.Date will ignore junk after the date so this takes less than 10 seconds on my not particularly fast laptop:

xx <- rep("10/17/2017 12:00:00 AM", 5000000) # test input
system.time(as.Date(xx, "%m/%d/%Y"))
## user  system elapsed 
## 9.57    0.20    9.82 

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

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