Julien P
Julien P

Reputation: 33

POSIXct in R, bug?

why is here a difference?

db$Produktionsanfang[1]="2019-01-07 06:10:00"
> x = as.numeric(as.POSIXct(db$Produktionsanfang,origin="1970-01-01", tz ="CET"))
> x[1]
[1] 1546815600
> as.POSIXct(1546815600,origin="1970-01-01")
[1] "2019-01-07 CET"

> as.numeric(as.POSIXct(db$Produktionsanfang[1],origin="1970-01-01",tz="CET"))
[1] 1546837800
> as.POSIXct(1546837800,origin="1970-01-01")
[1] "2019-01-07 06:10:00 CET"

> dput(head(db["Produktionsanfang"], 2))
structure(list(Produktionsanfang = c("2019-01-07 06:10:00", "2019-01-08 06:39:00"
)), row.names = 1:2, class = "data.frame")

Looks like the data.frame operation results in a bug? The second output is the correct one.

The problem is x = as.numeric(as.POSIXct(db$Produktionsanfang,origin="1970-01-01", tz ="CET")) is rounding the "value" "2019-01-07 06:10:00" to "2019-01-07", and also the next value "2019-01-08 06:39:00" to "2019-01-08" (and also all values out of the df). Thats not what I except by running this code.

The topic How can I keep midnight (00:00h) using strptime() in R? is not about this problem.

Can anyone explain? Thanks

Upvotes: 1

Views: 121

Answers (1)

Otto Kässi
Otto Kässi

Reputation: 3083

As note by @xilliam above, as.POSIXct drops the HH:MM when timestamp corresponds to midnight when printing. Hours and minutes are still saved.

E.g.

format(as.POSIXct(1546815600,origin="1970-01-01", tz='CET'), '%Y-%m-%d %M:%H')

[1] "2019-01-07 00:00"

Upvotes: 3

Related Questions