使用多种不同格式解析经过的时间/时间跨度/持续时间

时间:2015-08-05 10:01:45

标签: r datetime

我需要用几种不同的格式解析时间跨度,包括天,小时,分钟,秒.ms,由:分隔:%OS%H:%OS%H:%m:%OS%d:%H:%m:%OS。例如:

x <- c("28.6575", "1:14.0920", "1:5:38.1230", "5:23:59:38.7211") 

首先想到的是使用strptime将给定字符串解析为日期。此方法不适用于不包含时间跨度的所有部分的字符串。是否可以将部分格式字符串转换为可选字符串?

strptime("5:23:59:38.7211", "%d:%H:%M:%OS")
# [1] "2015-08-05 23:59:38"
strptime("1:5:38.1230", "%d:%H:%M:%OS")
# [1] NA # wanted: "2015-08-01 01:05:38"

另一种方法是将格式化的值转换为秒(例如1:14.0920 ~~> 74.0920 secs)。但是,我无法使用R。

找到一种方便的方法

2 个答案:

答案 0 :(得分:2)

这是@Konrad Rudolph评论的扩展版本:

function magicline() {
				  var $el, topPos, newHeight;
				  $mainNav = $("#nav_menu");
				  
				  $mainNav.append("<li id='magic_line'></li>");
				  var $magicLine = $("#magic_line");
					var isClicked = false;  // to show whether menu is clicked or not
					
					$magicLine.height($(".current_page_item").height())
						.css("top", $(".current_page_item a").position().top)
						.data("origTop", $magicLine.position().top)
						.data("origHeight", $magicLine.height());
					
					$("#nav_menu li").find("a").hover(function () {
						$el = $(this);
						topPos = $el.position().top;
						newHeight = $el.parent().height();
						
						$magicLine.stop().animate({
							top: topPos,
							height: newHeight
						});
					}, function () {
						if(!isClicked){         // if no item is clicked, take line to old position
							$magicLine.stop().animate({
								top: $magicLine.data("origTop"),
								height: $magicLine.data("origHeight")
							});
						}else{                 // else, just keep it there  
							isClicked = false;
							return false;
						}
					}).click(function(e){   // added click listener 
						isClicked = true;       // flag is set to indicate menu item is clicked.
						$magicLine.css({
							top: topPos,
							height: newHeight
						});                             
					});
				  
			}

答案 1 :(得分:1)

您还可以添加缺少的小时,分​​钟和天数据。

对于前者,如果v1是你的向量,你可以这样做:

res<-sapply(v1,function(x){
        if(str_count(x ,":")==2) paste0("1:",x)
        else if(str_count(x, ":") < 2)  paste0("1:",paste(rep("0:",2-str_count(x ,":")),collapse=""),x)
        else as.character(x)
        })
strptime(res, "%d:%H:%M:%OS")

它基本上计算冒号的数量,并添加任何缺失的内容以使其成为正确的格式。天数从1开始,所以当没有日期信息时我添加了1:

相关问题