2

I have a spreadsheet full of data with dates that look like this:

   Mon Jul 16 15:20:22 +0000 2012

Is there a way to convert these to R dates (preferably PST) without using regular expression or is there no other way? I'd appreciate ideas on doing this conversion efficiently.

Maiasaura
  • 32,226
  • 27
  • 104
  • 108

3 Answers3

8

Sure, just use strptime() to parse time from strings:

R> strptime("Mon Jul 16 15:20:22 +0000 2012", 
+           format="%a %b %d %H:%M:%S %z %Y")
[1] "2012-07-16 10:20:22 CDT"
R> 

which uses my local timezone (CDT). If yours is Pacific, you can set it explicitly as in

R> strptime("Mon Jul 16 15:20:22 +0000 2012", 
+           format="%a %b %d %H:%M:%S %z %Y", tz="America/Los_Angeles")
[1] "2012-07-16 08:20:22 PDT"
R> 

which looks right with a 7 hour delta to UTC.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
6

There's nearly a verbatim example of how to do this in the Examples section of ?strptime:

 # ?strptime example:
 ## An RFC 822 header (Eastern Canada, during DST)
 strptime("Tue, 23 Mar 2010 14:36:38 -0400",  "%a, %d %b %Y %H:%M:%S %z")
 # your data...
 strptime("Mon Jul 16 15:20:22 +0000 2012", "%a %b %d %H:%M:%S %z %Y")
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 2
    I hang my head in shame. I've never used `strptime`and was planning to use `stringr` functions to pick apart the pieces and typecast to date. – Maiasaura Aug 28 '12 at 21:04
  • 1
    @Maiasaura: don't worry, you can still probably get your Hadley fix via a lubridate function... :) – Joshua Ulrich Aug 28 '12 at 21:06
  • @Maiasaura: To paraphrase the wonderful Henry Spencer quote: _"Those who do not know date functions are condemned to reinvent them, poorly"_. See http://en.wikipedia.org/wiki/Henry_Spencer for more. – Dirk Eddelbuettel Aug 28 '12 at 21:25
0

This can also be done with lubridate package in tidyverse

library(lubridate)
parse_date_time("Mon Jul 16 15:20:22 +0000 2012", orders = "amdHMSzY")

which is what I prefer.

Kim
  • 4,080
  • 2
  • 30
  • 51