如何在 R 中为 POSIXct 对象添加天数 [英] How to add days to a POSIXct object in R

查看:34
本文介绍了如何在 R 中为 POSIXct 对象添加天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 POSIXct 对象添加特定的日期.我尝试了以下方法

I would like to add specific days to POSIXct object. I tried the below method

library(lubridate)
input_time = as.POSIXct("2018-05-05T14:14:05")
input_time +  lubridate::days(1) 

这使输出为2018-05-06 UTC";没有小时和秒 (14:14:05).我希望它的格式与 input_time (2018-05-06T14:14:05) 的格式相同.如何保留小时和秒信息

This gives the output as "2018-05-06 UTC" without the hours and seconds (14:14:05). I would like to have it in the same format as input_time (2018-05-06T14:14:05). How to retain the hours and seconds information

推荐答案

as.POSIXct 未测试您的时间格式.这就是你得到这个结果的原因.

Your time format is not being tested by as.POSIXct. This is why you get this result.

您可以使用以下格式来使其正确:

You can use the following format to get it correct:

library(lubridate)

# note the format option to get it correct
input_time = as.POSIXct("2018-05-05T14:14:05", format = "%Y-%m-%dT%H:%M:%OS")
input_time + lubridate::days(1)

[1] "2018-05-06 14:14:05 UTC"

或者只是使用 lubridate 的所有函数:

or just use everything with functions from lubridate:

input_time <- lubridate::ymd_hms("2018-05-05T14:14:05")
input_time + lubridate::days(1)

[1] "2018-05-06 14:14:05 UTC"

这篇关于如何在 R 中为 POSIXct 对象添加天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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