LoginSignup
2
1

More than 5 years have passed since last update.

R: POSIXct -> Date で日付がズレる

Last updated at Posted at 2016-09-23

何も考えずにPOSIXctクラスをDateクラスに変換すると、ときどき怖いことが起こる。

a <- as.POSIXct("2016-09-23")
print(a)
#[1] "2016-09-23 JST"
as.Date(a)
#[1] "2016-09-22"

どうやらタイムゾーンの関係らしい。

as.Date(a, tz = "Japan")
#[1] "2016-09-23"

POSIXltクラスなら大丈夫(?)

b <- as.POSIXlt('2016-9-23')
as.Date(b)
#[1] "2016-09-23"

でも僕は怖いので一度文字列に変換する処理を挟んだりします。

as.Date(strftime(a, "%Y-%m-%d"))
[1] "2016-09-23"
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1