[R] Convert to date and time of the year

David Winsemius dwinsemius at comcast.net
Tue Mar 19 04:42:33 CET 2013


On Mar 18, 2013, at 8:05 PM, Ben Tupper wrote:

> Hi Janesh,
> 
> On Mar 18, 2013, at 10:49 PM, Janesh Devkota wrote:
> 
>> Dear R Users, 
>> 
>> I have data for more than 3 years. For each year I want to find the day
>> corresponding to Jaunary 1 of that year. For example:
>> 
>>> x <- c('5/5/2007','12/31/2007','1/2/2008')
>> 
>>> #Convert to day of year (julian date) -
>> 
>>> strptime(x,"%m/%d/%Y")$yday+1
>> 
>> [1] 125 365   2
>> 
>> I want to know how to do the same thing but with time added. But I still get
>> the day not time. Can anyone suggest what is the better way to find the
>> julian date with date and time ?
>> 
>>> x1 <- c('5/5/2007 02:00','12/31/2007 05:58','1/2/2008 16:25')
>> 
>>> #Convert to day of year (julian date) -
>> 
>>> strptime(x1,"%m/%d/%Y %H:%M")$yday+1
>> 
>> [1] 125 365   2
>> 

> julian(strptime(x1,"%m/%d/%Y %H:%M"))
Time differences in days
[1] 13638.38 13878.58 13881.02
attr(,"tzone")
[1] ""
attr(,"origin")
[1] "1970-01-01 GMT"


And a more ham-handed way:

> as.numeric(strptime(x1,"%m/%d/%Y %H:%M"))/(24*3600)
[1] 13638.38 13878.58 13881.02

> 
> Would this do it for you?
> 
> x1 <- c('5/5/2007 02:00','12/31/2007 05:58','1/2/2008 16:25')
> x1 <- as.POSIXct(x1, format = "%m/%d/%Y %H:%M")
> 
> day <- as.numeric(format(x1, "%j")) 
> hour <- as.numeric(format(x1, "%H"))/24 
> minute <- as.numeric(format(x1, "%M"))/(60*24) 
> second <- as.numeric(format(x1, "%S"))/(60*60*24)
> 
> day + hour + minute + second
> 
> [1] 125.083333 365.248611   2.684028
> 
> Cheers,
> Ben
> 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list