How to convert date and time into a numeric value
You can do this with base R just fine, but there are some shortcuts for common date formats in the lubridate package:
library(lubridate)
d <- ymd_hms("30/11/2012 14:35")
> as.numeric(d)
[1] 1921407275
From ?POSIXct
:
Class "POSIXct" represents the (signed) number of seconds since the beginning of 1970 (in the UTC timezone) as a numeric vector.
Related videos on Youtube
user3439171
Updated on September 16, 2022Comments
-
user3439171 over 1 year
As a new and self taught R user I am struggling with converting date and time values characters into numbers to enable me to group unique combinations of data. I'm hoping someone has come across this before and knows how I might go about it.
I'd like to convert a field of DateTime data (30/11/2012 14:35) to a numeric version of the date and time (seconds from 1970 maybe??) so that I can back reference the date and time if needed.
I have search the R help and online help and only seem to be able to find POSIXct, strptime which seem to convert the other way in the examples I've seen.
I will need to apply the conversion to a large dataset so I need to set the formatting for a field not an individual value.
I have tried to modify some python code but to no avail...
Any help with this, including pointers to tools I should read about would be much appreciated.
-
user3439171 about 10 yearsThis is great, thanks for the quick response - this code as an example makes sense and works for me. However I am still struggling to apply this to a field with format %d/%m/%Y %H:%M (DateTime) instead of just applying to one defined data point. I just can't get my head around how to generically apply a format to then be applied to the field from this. Thank you in advance for your patience. Lou
-
Ari B. Friedman about 10 years
ymd_hms()
takes in a vector (could be a column of a data.frame) and returns a vector of the same length, with each element converted. You can then reassign that vector back to the same column of your data.frame and it will have converted the whole column to POSIXct. -
user3439171 about 10 yearsThank you for your time...I think I understand your response and have been trying to give a vector (datime) to ymd_hms as below but am struggling to get the result I'm after still ATTEMPT 1: > ymd_hms("%d/%m/%Y %H:%M") [1] NA Warning message: All formats failed to parse. No formats found. ATTEMPT 2: > datimeformat<-ymd_hms(datime,format = "%d/%m/%Y %H:%M") Warning message: 191 failed to parse. > as.numeric(datime) [1] 14 14 15 15 15 15 15 this gives unique values but not logically reversible. Sorry to be taking a while to work this out. Lou