Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a datetime object from separate date fields?

Tags:

date

datetime

r

I have a dataset like this:

    Year MM DD HH
158 2010  7  1  5
159 2010  7  1  5
160 2010  7  1  6
161 2010  7  1  6

structure(list(Year = c(2010L, 2010L, 2010L, 2010L), MM = c(7L, 
7L, 7L, 7L), DD = c(1L, 1L, 1L, 1L), HH = c(5L, 5L, 6L, 6L)), .Names = c("Year", 
"MM", "DD", "HH"), row.names = 158:161, class = "data.frame")

How can I create a one datetime object from this data set (new column for this data)?

like image 586
jrara Avatar asked Jan 24 '12 10:01

jrara


People also ask

How do I create a datetime object in R?

To create a Date object from a simple character string in R, you can use the as. Date() function. The character string has to obey a format that can be defined using a set of symbols (the examples correspond to 13 January, 1982): %Y : 4-digit year (1982)

How do you create a date object in Python?

To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.


2 Answers

You can now do this in lubridate using make_date or make_datetime:

From the cran doc:

make_datetime(year = 1970L, month = 1L, day = 1L, hour = 0L, min = 0L,
sec = 0, tz = "UTC")

make_date(year = 1970L, month = 1L, day = 1L)
like image 146
Preston Avatar answered Oct 18 '22 21:10

Preston


There are a few options, here's one (where x is your data.frame):

x$datetime <- ISOdatetime(x$Year, x$MM, x$DD, x$HH, 0, 0)

You can pass in the correct time zone if need be, see ?ISOdatetime.

like image 39
mdsumner Avatar answered Oct 18 '22 21:10

mdsumner