1

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

Julien P
  • 21
  • 4
  • Please provide reproducible data. `dput(head(db["Produktionsanfang"], 2))` should be enough. – s_baldur Dec 10 '19 at 10:33
  • Is it because as.POSIXct() is rounding to the day in the first example, since 1546815600 is precisely at a 24-hour period? – xilliam Dec 10 '19 at 10:36
  • 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") – Julien P Dec 10 '19 at 10:38
  • You need to use `as.POSIXct(..., tz = "CET")` for your code to be reproducible. – asachet Dec 10 '19 at 10:38
  • x = as.numeric(as.POSIXct(stranggussdatenbank$Produktionsanfang,origin="1970-01-01", tz ="CET")) This brings the same "wrong" result. – Julien P Dec 10 '19 at 10:50
  • 1
    Does this answer your question? [How can I keep midnight (00:00h) using strptime() in R?](https://stackoverflow.com/questions/37089536/how-can-i-keep-midnight-0000h-using-strptime-in-r) – jay.sf Dec 10 '19 at 11:01
  • No. The problem is `x = as.numeric(as.POSIXct(stranggussdatenbank$Produktionsanfang,origin="1970-01-01", tz ="CET"))` is rounding the "value" "2019-01-07 06:10:00" to "2019-01-07". Thats not what I except by running this code. – Julien P Dec 10 '19 at 11:05

1 Answers1

3

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"
Otto Kässi
  • 2,943
  • 1
  • 10
  • 27