-9

The timestamps I have as character class are in this format: 1/28/15 16:34 . How do I covert it to an R time stamp format and then also extract the hour of the day, day of the week and year separately as well?

Jaap
  • 81,064
  • 34
  • 182
  • 193
user251385
  • 31
  • 2
  • 1
    `strptime('1/28/15 16:34', '%m/%d/%y %H:%M')` – Jaap Jan 05 '17 at 18:08
  • Also how do i extract time of day and day of week and year into 3 separate variables after this conversion? I say after conversion as I also need the complete timestamp which you provided in your answer very well. Also, why is everyone downvoting me!!! – user251385 Jan 05 '17 at 18:19
  • 1
    `strptime('1/28/15 16:34', '%m/%d/%y %H:%M')$wday` gives `3` (which is wednesday) – Jaap Jan 05 '17 at 18:20
  • 4
    The reason is quite obvious to me: you didn't show any research effort (which is also suggested when you hover over the downvote button). Just typing the [two tags in the search box](http://stackoverflow.com/questions/tagged/r+timestamp) would have given you a nice collection of answers on converting character strings to datetime format. See also: [ask]. – Jaap Jan 05 '17 at 18:26
  • see also http://stackoverflow.com/q/15072955/3817004 – Uwe Jan 06 '17 at 10:07

1 Answers1

1

You can use strptime function in this way:

my_time = strptime("1/28/15 16:34", "%m/%d/%y %H:%M")

Note in particular the %m and the %y to say, respectively, that months will be written with 1 character from Jan to Sept and year will be written with 2 character.

For example, if you need to convert "01/28/2015" you need %M and %Y:

my_time = strptime('01/28/2015 16:34', '%M/%d/%Y %H:%M')

To extract the day of week and the hour:

library(lubridate)
week_day = wday(my_time) # or wday(my_time, label=T) if you want the weekday label (Wed in this case)
day_hour = hour(my_time)
enneppi
  • 1,029
  • 2
  • 15
  • 33
  • Also how do i extract time of day and day of week and year into 3 separate variables after this conversion? I say after conversion as I also need the complete timestamp which you provided in your answer very well. Also, why is everyone downvoting me!!! – user251385 Jan 05 '17 at 18:18