How to print UTC timestamp using datatable (DT package) in Rmarkdown?
I have timestamps stored in different timezones that I would like to include in a datatable using a package DT
in the document rmarkdown
.
I would like to display the timestamp in the saved timezone, but datatable
converts it to UTC for some reason . The behavior when I use print
is what I want, but the format is not very nice.
How can I achieve the same behavior with datatable
and print
?
Here's a minimal working example file rmarkdown
:
---
title: "MinorQ"
output: html_document
---
```{r setup}
library(DT)
df=data.frame(timestamp=as.POSIXct("2017-01-01 12:34:56",tz="CET"))
df$tzone=attr(df$timestamp,"tzone")
datatable(df)
print(df)
```
source to share
As mentioned in my comment, you can simply convert POSIXct elements to symbol:
input <- format(as.POSIXct("2017-01-01 12:34:56", tz = "CET"), format = '%F %T %Z')
str(input)
# chr "2017-01-01 12:34:56 CET"
This does not mean that you cannot use different time zones. When reading from a table, you can use gsub
to get your dates with the correct timezone:
# First gsub: remove all capital letters (so only date and time remain)
# Sec. gsub: remove all characters exept capital letters (so only CET, UTC, etc. remain).
out <- as.POSIXct(gsub(input, pattern = "[A-Z]", replacement = ""),
format = '%F %T',
tz = gsub(input, pattern = "[^A-Z]", replacement = ""))
str(out)
# POSIXct[1:1], format: "2017-01-01 12:34:56"
lubridate::tz(out)
# [1] "CET"
source to share