使用%b格式化日期时出现R strptime问题 [英] R strptime issue when using %b to format a date

查看:81
本文介绍了使用%b格式化日期时出现R strptime问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标记为重复之前,我尝试了其他一些解决方案,即:

Before marking as duplicate, I've tried a few other solutions, namely these:

R,strptime(),%b,试图将字符转换为日期格式

strptime,如POSIXct和日期返回意外的NA

但似乎都不适合我。

我正在尝试将时间格式 Dec-18 转换为POSIXct时间(将为 2018-12 -01 )。我正在尝试将 strptime %b %y 这样实现:

I'm trying to convert a time format Dec-18 to a POSIXct time (would be 2018-12-01 in this case). I'm attempting to use strptime with %b and %y to achieve this as so:

> strptime("Dec-18", format = "%b-%y")
[1] NA

但是显然它不起作用。我正在阅读有关语言环境之类的信息,但是上述解决方案不适用于我。我尝试了以下操作:

But obviously it is not working. I'm reading a out about "locales" and such, but the above solutions did not work for me. I attempted the following:

> Sys.setlocale("LC_TIME", "C")
[1] "C"
> strptime("Dec-18", format = "%b-%y")
[1] NA

还建议使用此语言环境 Sys.setlocale( LC_TIME, en_GB.UTF-8),但是当出现错误尝试使用此功能:

It was also suggested to use this locale, Sys.setlocale("LC_TIME", "en_GB.UTF-8"), but I get an error when trying to use this:

> Sys.setlocale("LC_TIME", "en_GB.UTF-8")
[1] ""
Warning message:
In Sys.setlocale("LC_TIME", "en_GB.UTF-8") :
  OS reports request to set locale to "en_GB.UTF-8" cannot be honored

对此不知所措。基于此,我的缩写月份似乎是正确的:

Kind of at a loss for what to do here. My abbreviated months seem right based off this:

> month.abb
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

以下是我正在运行的R版本:

Here's the version of R that I am running:

R version 3.5.3 (2019-03-11) -- "Great Truth"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

谢谢。

推荐答案

最简单的解决方案是:

as.Date(x = paste0("01-", "Dec-18"),
        format = "%d-%b-%y")
#> [1] "2018-12-01"

format(x = as.Date(x = paste0("01-", "Dec-18"),
                   format = "%d-%b-%y"),
       format = "%b-%y")
#> [1] "Dec-18"

在2019-05-15由< a href = https://reprex.tidyverse.org rel = nofollow noreferrer> reprex软件包(v0.2.1)

Created on 2019-05-15 by the reprex package (v0.2.1)

R 不能将12月18日识别为日期。添加 01-,以便它可以将其检测为日期,然后根据需要显示。

R doesn't recognise Dec-18 as date. Add a 01- so that it can detect it as date, and then display as you prefer.

这篇关于使用%b格式化日期时出现R strptime问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆