0

How can i find week_of_month and week_of_year from datetime in R script ?

Example: for datetime 2016-09-27 00:00:07.477, week_of_month is 5 and week_of_year is 39

I am getting day_of month from weekdays.Date("2016-09-27 00:00:07.477").

Likewise i want to get week_of_month and week_of_year.

Gaurav
  • 1,965
  • 2
  • 16
  • 32
  • 4
    Have you read this? http://stackoverflow.com/questions/27116645/r-week-function-returns-unexpected-values and http://stackoverflow.com/questions/25199851/r-how-to-get-the-week-number-of-the-month – J_F Oct 10 '16 at 14:20
  • Got solution from this link http://stackoverflow.com/a/25202142/1448357 for `week_of_month. and formatting date by `%U` gives week_of_year. – Gaurav Oct 13 '16 at 02:44

1 Answers1

6

You can do most of that with base R:

R> dt <- as.POSIXct("2016-09-27 00:00:07.477")   ## ISO8601 parsing
R> dt
[1] "2016-09-27 00:00:07.476 CDT"
R> plt <- as.POSIXlt(dt)
R> plt$mday                           # day of the month
[1] 27
R> plt$yday                           # day of the year
[1] 270
R> plt$wday                           # day of the week
[1] 2
R> 

For some you need to look at help(strptime)

R> format(plt, "%U")                  # week of the year
[1] "39"
R> 
R> format(plt, "%V")                  # alternate definition
[1] "39"
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725