Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Date as "YYYY-Mon" with Lubridate?

I would like to create a vector of dates between two specified moments in time with step 1 month, as described in this thread (Create a Vector of All Days Between Two Dates), to be then converted into factors for data visualization.

However, I'd like to have the dates in the YYYY-Mon, ie. 2010-Feb, format. But so far I managed only to have the dates in the standard format 2010-02-01, using a code like this:

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"

How can I change the format to YYYY-Mon?

like image 611
Fabio Capezzuoli Avatar asked Sep 23 '18 14:09

Fabio Capezzuoli


People also ask

What time zone is the datetime column in lubridate?

At the moment, the datetime column is in UTC, or Coordinated Universal Time because it’s the default when lubridate parses dates. To change this, you can use the function force_tz ():

What is the lubridate package used for?

The lubridate package provides several different helper functions designed to convert character objects to dates in an intuitive, and more lenient way than specifying the format in as.Date ().

How to make sure the date format in a variable is 'DD-Mon-YYYY'?

user11090588 wrote: How to make sure, that the date format in a variable of varchar is 'DD-MON-YYYY' . If there is anything else, exception needs to be raised. DATE datatype have NO format. if s <> to_char (to_date (s, 'DD-MON-YYYY'), 'DD-MON-YYYY') then

Does lubridate work with 2-digit or 4-digit years?

Note that the above functions work best with 4-digit years. 2-digit years can produce unexpected results, as lubridate attempts to guess the century.


1 Answers

You can use format():

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

To create the vector, use seq():

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

Obs: Use capital 'B' for full month name: '%Y-%B'.

like image 150
Augusto Fadel Avatar answered Oct 10 '22 00:10

Augusto Fadel