格式化指定 LC_TIME 的时间对象而不更改区域设置

发布于 2025-01-16 09:16:51 字数 635 浏览 3 评论 0原文

有没有办法在 R 中格式化 POSIXct 对象并在该调用中指定 LC_TIME ?

即我有这段代码以德语格式返回对象

t <- Sys.time()
fmt <- "%a, %d %b %Y %H:%M:%S GMT"
format(t, fmt)
#> [1] "Mi, 23 Mrz 2022 14:57:50 GMT"

Sys.getlocale("LC_TIME")
#> [1] "German_Germany.1252"

我想要的格式可以通过设置 LC_TIME 来实现,但这不是我想要的。相反,我想找到一个解决方案,而不更改我的 R 会话或区域设置的选项。

Sys.setlocale("LC_TIME", "C")
format(t, fmt)
#> [1] "Wed, 23 Mar 2022 14:57:50 GMT"
# correct output, but changing the locale :(

理想情况下,我想要像 format(t, fmt, LC_TIME = "C") 或类似的东西,具有最小的外部依赖性,并且不改变任何其他内容......

Is there a way to format a POSIXct object in R and specifying the LC_TIME in that call?

Ie I have this code which returns the object in the German format

t <- Sys.time()
fmt <- "%a, %d %b %Y %H:%M:%S GMT"
format(t, fmt)
#> [1] "Mi, 23 Mrz 2022 14:57:50 GMT"

Sys.getlocale("LC_TIME")
#> [1] "German_Germany.1252"

The format I want can be achieved by setting the LC_TIME, but this is not what I want. Instead I want to find a solution without changing the options of my R session or my locale.

Sys.setlocale("LC_TIME", "C")
format(t, fmt)
#> [1] "Wed, 23 Mar 2022 14:57:50 GMT"
# correct output, but changing the locale :(

Ideally, I want something like format(t, fmt, LC_TIME = "C") or similar with minimal external dependencies and not changing anything else...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

得不到的就毁灭 2025-01-23 09:16:51

我找不到完美的解决方案,但有一个使用 local() 的解决方法,具体取决于您的目的。 local() 让您可以像在函数中一样定义变量,这样您的全局环境就不会受到干扰。

fmt <- "%a, %d %b %Y %H:%M:%S GMT"
local({
  locale <- Sys.getlocale("LC_TIME")
  Sys.setlocale("LC_TIME", "C")
  final_date <- format(Sys.time(), fmt)
  Sys.setlocale("LC_TIME", locale)
  return(final_date)})
#> [1] "Wed, 25 May 2022 12:03:36 GMT"

不幸的是,系统区域设置已更改,因此您应该在最后使用 Sys.setlocale("LC_TIME", locale) 将其恢复。此方法的优点是您可以通过对变量进行零更改来获得所需的内容(否则将创建变量 locale)。

I couldn't find a perfect solution but there is a workaround using local(), depending on your purposes. local() let you define variables as in a function, so your global environment won't be disturbed.

fmt <- "%a, %d %b %Y %H:%M:%S GMT"
local({
  locale <- Sys.getlocale("LC_TIME")
  Sys.setlocale("LC_TIME", "C")
  final_date <- format(Sys.time(), fmt)
  Sys.setlocale("LC_TIME", locale)
  return(final_date)})
#> [1] "Wed, 25 May 2022 12:03:36 GMT"

Unfortunately the system locale is changed so you should use Sys.setlocale("LC_TIME", locale) at the end to turn it back. The advantage of this method is that you can get what you want with zero changes in your variables (the variable locale would be created otherwise).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文