将日期时间列拆分为日期和时间变量 [英] Split date-time column into Date and time variables

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

问题描述

我有一个日期-时间列开始,格式为 Y-m-d H:M:S。我想将此列拆分为一个日期和时间

I have a 'date-time column 'Start' in the format "Y-m-d H:M:S". I want to split this column into a "Date" and a "time" column.

我尝试了以下操作:

df$Date <- sapply(strsplit(as.character(df$Start), " "), "[", 1)
df$Time <- sapply(strsplit(as.character(df$Start), " "), "[", 2)

但是,如果我使用功能 str(df)

This works, however, if I use the function str(df)

# 'data.frame':   18363 obs. of  19 variables:<br>
#  $ Start    : Factor w/ 67 levels "2013-09-01 08:07:41.000",..: 1 1 1 1 1 1 1 1 1 1 ...
# [snip]

所以现在我只需要知道如何从 factor 设置为时间和日期。

So now I only need to know how to convert the time and date from factor to 'time' and 'date'.

推荐答案

df$Date <- as.Date(df$Start) # already got this one from the answers above
df$Time <- format(as.POSIXct(df$Start), format = "%H:%M:%S") 

使用作为日期将开始转换为类 Date 的变量。对于时间变量,我们首先将开始转换为 POSIXct 。然后使用 format 将时间分量提取为字符串。

Use as.Date to convert 'Start' to a variables of class Date. For the time variable, we first convert 'Start' to POSIXct. Then use format to extract the time component as a string.

这篇关于将日期时间列拆分为日期和时间变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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