简体   繁体   English

如何在Rmarkdown中使用数据表(DT包)打印非UTC时间戳?

[英]How can I print a non UTC timestamp using datatable (DT package) in Rmarkdown?

I have some timestamps stored in different time-zones that I would like to include in a datatable using DT package within a rmarkdown document. 我有一些时间戳存储在不同的时区,我想在rmarkdown文档中使用DT包包含在数据rmarkdown

I would like to display the timestamp in the stored time-zone but for some reason datatable converts it to UTC. 我想,以显示存储的时区,但由于某些原因,时间戳datatable将其转换为UTC。 The behaviour when I use print is what I want but the format is not nice. 我使用print时的行为是我想要的但是格式不好。

How can I achieve the same behaviour with datatable and print ? 如何使用datatableprint实现相同的行为?

Here a minimal working example of the rmarkdown 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)
```

As mentioned in my comment you could just convert your POSIXct elements to character: 正如我在评论中提到的,你可以将你的POSIXct元素转换为字符:

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 timezones. 这并不意味着您不能使用不同的时区。 When reading from the table you could use gsub to get your dates with the correct timezone: 从表中读取时,您可以使用gsub以正确的时区获取日期:

# 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM