格式化指定 LC_TIME 的时间对象而不更改区域设置
有没有办法在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找不到完美的解决方案,但有一个使用
local()
的解决方法,具体取决于您的目的。local()
让您可以像在函数中一样定义变量,这样您的全局环境就不会受到干扰。不幸的是,系统区域设置已更改,因此您应该在最后使用
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.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 variablelocale
would be created otherwise).