Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert date and time into a numeric value

Tags:

datetime

r

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.

like image 999
user3439171 Avatar asked Mar 20 '23 04:03

user3439171


1 Answers

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.

like image 166
Ari B. Friedman Avatar answered Mar 31 '23 20:03

Ari B. Friedman