将年份周字符串转换为日期 [英] convert year week string to date

查看:187
本文介绍了将年份周字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据集中有一列字符串,其格式设置为年份星期(例如,"201401"等于2014年4月7日,即该年份的第一个会计周)

I have a column of strings in my data set formatted as year week (e.g. '201401' is equivalent to 7th April 2014, or the first fiscal week of the year)

我正在尝试将它们转换为正确的日期,以便以后可以使用它们,但是我总是收到给定年份(特别是4月14日)的贵妇日期.

I am trying to convert these to a proper date so I can manipulate them later, however I always receive the dame date for a given year, specifically the 14th of April.

例如

test_set <- c('201401', '201402', '201403')
as.Date(test_set, '%Y%U')

给我:

[1] "2014-04-14" "2014-04-14" "2014-04-14"

推荐答案

尝试如下操作:

> test_set <- c('201401', '201402', '201403')
> 
> extractDate <- function(dateString, fiscalStart = as.Date("2014-04-01")) {
+   week <- substr(dateString, 5, 6)
+   currentDate <- fiscalStart + 7 * as.numeric(week) - 1
+   currentDate
+ }
> 
> extractDate(test_set)
[1] "2014-04-07" "2014-04-14" "2014-04-21"

基本上,我要从年初开始提取几周,将其转换为几天,然后将该天数添加到会计年度的开始(少于1天以使事情排成一行).

Basically, I'm extracting the weeks from the start of the year, converting it to days and then adding that number of days to the start of the fiscal year (less 1 day to make things line up).

这篇关于将年份周字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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