从R中的datetime创建日期列 [英] Create date column from datetime in R

查看:28
本文介绍了从R中的datetime创建日期列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,并且是一名狂热的SAS程序员,只是很难把头放在R上.

I am new to R and I am an avid SAS programmer and am just having a difficult time wrapping my head around R.

在数据框中,我有一个日期时间列,格式为 POSIXct ,下面的列显示为"2013-01-01 00:53:00" .我想使用提取日期的函数和提取小时的列来创建日期列.在理想的世界中,我希望能够提取数据框中所有的日期,年,日,月,时间和小时,以在数据框中创建这些其他列.

Within a data frame I have a date time column formatted as a POSIXct with the following the column appearing as "2013-01-01 00:53:00". I would like to create a date column using a function that extracts the date and a column to extract the hour. In an ideal world I would like to be able to extract the date, year, day, month, time and hour all within the data frame to create these additional columns within the data frame.

推荐答案

始终谨慎使用 as.Date(as.POSIXct(...)):

例如,对于我在澳大利亚:

E.g., for me in Australia:

df <- data.frame(dt=as.POSIXct("2013-01-01 00:53:00"))
df
#                   dt
#1 2013-01-01 00:53:00

as.Date(df$dt)
#[1] "2012-12-31"

您会发现这是有问题的,因为日期不匹配.如果您的 POSIXct 对象不在 UTC 时区中,则会遇到问题,因为 as.Date 默认为 tz ="UTC".详情请参阅此处: as.Date(as.POSIXct())给出了日期错误?
为了安全起见,您可能需要匹配时区:

You'll see that this is problematic as the dates don't match. You'll hit problems if your POSIXct object is not in the UTC timezone as as.Date defaults to tz="UTC" for this class. See here for more info: as.Date(as.POSIXct()) gives the wrong date?
To be safe you probably need to match your timezones:

as.Date(df$dt,tz=Sys.timezone()) #assuming you've just created df in the same session:
#[1] "2013-01-01"

或更安全的选择#1:

df <- data.frame(dt=as.POSIXct("2013-01-01 00:53:00",tz="UTC"))
as.Date(df$dt)
#[1] "2013-01-01"

或更安全的选择#2:

as.Date(df$dt,tz=attr(df$dt,"tzone"))
#[1] "2013-01-01"

或者使用 format 提取 POSIXct 对象的一部分:

Or alternatively use format to extract parts of the POSIXct object:

as.Date(format(df$dt,"%Y-%m-%d"))
#[1] "2013-01-01"
as.numeric(format(df$dt,"%Y"))
#[1] 2013
as.numeric(format(df$dt,"%m"))
#[1] 1
as.numeric(format(df$dt,"%d"))
#[1] 1

这篇关于从R中的datetime创建日期列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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