【问题标题】:How to format a Date as "YYYY-Mon" with Lubridate?如何使用 Lubridate 将日期格式化为“YYYY-Mon”?
【发布时间】:2019-02-27 05:39:51
【问题描述】:

我想在步骤 1 个月内创建两个指定时刻之间的日期向量,如本线程 (Create a Vector of All Days Between Two Dates) 中所述,然后将其转换为数据可视化因子。

但是,我希望在 YYYY-Mon 中有日期,即。 2010 年 2 月,格式。但到目前为止,我只设法使用标准格式 2010-02-01 的日期,使用如下代码:

require(lubridate)
first <- ymd_hms("2010-02-07 15:00:00 UTC")
start <- ymd(floor_date(first, unit="month"))

last <- ymd_hms("2017-10-29 20:00:00 UTC")
end <- ymd(ceiling_date(last, unit="month"))

> start
[1] "2010-02-01"

> end
[1] "2017-11-01"

如何将格式更改为 YYYY-Mon?

【问题讨论】:

    标签: r date format lubridate


    【解决方案1】:

    你可以使用format():

    start %>% format('%Y-%b')
    

    要创建向量,请使用seq():

    seq(start, end, by = 'month') %>% format('%Y-%b')
    

    Obs:使用大写的“B”作为完整的月份名称:'%Y-%B'

    【讨论】:

    • 这行得通,谢谢。现在,如何保持'%Y-%b'格式从开始到结束的按月顺序排列?
    • 太棒了!你可以使用seq()seq(start, end, by = 'month') %&gt;% format('%Y-%b')
    • 是的,我也是自己来的。但无论如何,我感谢您的帮助。
    • 请注意,format() 是一个基本 R 函数,会将向量从日期时间更改为字符。
    猜你喜欢
    • 2010-12-13
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2023-03-26
    • 2020-02-03
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多