如何在 POSIXct 中开始一天 [英] How to get the beginning of the day in POSIXct

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

问题描述

我的一天从 2016-03-02 00:00:00 开始.不是 2016-03-02 00:00:01.

My day starts at 2016-03-02 00:00:00. Not 2016-03-02 00:00:01.

如何在本地时间 POSIXct 中获得一天的开始?

How do I get the beginning of the day in POSIXct in local time?

我的困惑可能是因为 R 将其视为 2016-03-01 的结束日期?鉴于 R 使用 ISO 8601?

My confusing probably comes from the fact that R sees this as the end-date of 2016-03-01? Given that R uses an ISO 8601?

例如,如果我尝试使用 Sys.Date() 查找一天的开始:

For example if I try to find the beginning of the day using Sys.Date():

as.POSIXct(Sys.Date(), tz = "CET")
"2016-03-01 01:00:00 CET"

哪个不正确 - 但还有其他方法吗?

Which is not correct - but are there other ways?

我知道我可以用一个简单的方法来破解

I know I can hack my way out using a simple

as.POSIXct(paste(Sys.Date(), "00:00:00", sep = " "), tz = "CET")

但是必须有更正确的方法来做到这一点?优选基R.

But there has to be a more correct way to do this? Base R preferred.

推荐答案

这是一个单一的命令---但是你想要 as.POSIXlt():

It's a single command---but you want as.POSIXlt():

R> as.POSIXlt(Sys.Date())
[1] "2016-03-02 UTC"
R> format(as.POSIXlt(Sys.Date()), "%Y-%m-%d %H:%M:%S")
[1] "2016-03-02 00:00:00"
R> 

只有当转换为 POSIXct 时,时区偏移到 UTC(对我来说是六个小时)才会输入:

It is only when converting to POSIXct happens that the timezone offset to UTC (six hours for me) enters:

R> as.POSIXct(Sys.Date())
[1] "2016-03-01 18:00:00 CST"
R> 

不用说,通过包装您可以获得所需的类型:

Needless to say by wrapping both you get the desired type and value:

R> as.POSIXct(as.POSIXlt(Sys.Date()))
[1] "2016-03-02 UTC"
R> 

再次提交,不需要 lubridate 或其他非 Base R 包.

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

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