将POSIXct日期时间转换为Date时发生意外日期-时区问题? [英] Unexpected date when converting POSIXct date-time to Date - timezone issue?

查看:91
本文介绍了将POSIXct日期时间转换为Date时发生意外日期-时区问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用 as.Date POSIXct 日期时间强制为 Date 时,似乎返回了错误的日期./p>

我怀疑这与时区有关.我在 as.Date 中尝试了 tz 参数,但是没有给出预期的日期.

 #POSIXct返回每月的第24天数据$时间[3]#[1]"2020-03-24 00:02:00 IST"类(data $ Time [3])#[1]"POSIXct";"POSIXt"#强制转换为Date,返回23as.Date(data $ Time [3])#[1]"2020-03-23";#尝试时区参数,不走运as.Date(data $ Time [3],tz ="IST")#[1]"2020-03-23";# 警告信息:#在as.POSIXlt.POSIXct(x,tz = tz)中:未知时区'IST'Sys.timezone()#[1]亚洲/Calcutta" 

任何想法在这里可能出什么问题吗?

解决方案

使用注释末尾的设置,我们可以使用以下任何一种方法:

 #与print(x)显示的日期相同as.Date(as.character(x))## [1]"2020-03-24";#使用x中存储的时区(如果为",则使用系统时区)as.Date(x,tz = attr(x,"tzone"))## [1]"2020-03-24";#使用系统时区as.Date(x,tz =")## [1]"2020-03-24";#使用系统时区as.Date(x,tz = Sys.timezone())## [1]"2020-03-24";#使用指示的时区as.Date(x,tz ="Asia/Calcutta")## [1]"2020-03-24"; 

注意

我们假设此设置.

  Sys.setenv(TZ ="Asia/Calcutta")x<-结构(1584988320,类= c("POSIXct","POSIXt"),tzone =")R.version.string## [1]"R版本4.0.2已修补(2020-06-24 r78745)" 

When I try to coerce a POSIXct date-time to a Date using as.Date, it seems to return wrong date.

I suspect it has got something to do with the time zone. I tried the tz argument in as.Date, but it didn't give the expected date.

# POSIXct returns day of month 24  
data$Time[3]
# [1] "2020-03-24 00:02:00 IST"

class(data$Time[3])
# [1] "POSIXct" "POSIXt"

# coerce to Date, returns 23 
as.Date(data$Time[3])
# [1] "2020-03-23"

# try the time zone argument, without luck
as.Date(data$Time[3], tz = "IST")
# [1] "2020-03-23"
# Warning message:
# In as.POSIXlt.POSIXct(x, tz = tz) : unknown timezone 'IST' 

Sys.timezone()
# [1] "Asia/Calcutta"

Any ideas what may be going wrong here?

解决方案

Using the setup in the Note at the end we can use any of these:

# same date as print(x) shows
as.Date(as.character(x))
## [1] "2020-03-24"

# use the time zone stored in x (or system time zone if that is "")
as.Date(x, tz = attr(x, "tzone"))
## [1] "2020-03-24"

# use system time zone
as.Date(x, tz = "")
## [1] "2020-03-24"

# use system time zone
as.Date(x, tz = Sys.timezone())
## [1] "2020-03-24"

# use indicated time zone
as.Date(x, tz = "Asia/Calcutta")
## [1] "2020-03-24"

Note

We have assumed this setup.

Sys.setenv(TZ = "Asia/Calcutta")
x <- structure(1584988320, class = c("POSIXct", "POSIXt"), tzone = "")

R.version.string
## [1] "R version 4.0.2 Patched (2020-06-24 r78745)"

这篇关于将POSIXct日期时间转换为Date时发生意外日期-时区问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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