R Convert String Date (E.G. "October 1, 2014") to Date Format

R convert string date (e.g. October 1, 2014) to Date format

Try:

v <- c("October 1, 2014", "June 14, 2014") 
as.Date(v, "%B %d,%Y")

Which gives:

#[1] "2014-10-01" "2014-06-14"

Or

strptime(v, "%B %d,%Y")

Which gives:

#[1] "2014-10-01 EDT" "2014-06-14 EDT"

Benchmark

largev <- rep(v, 10e5)

library(microbenchmark)
microbenchmark(
as.Date = as.Date(largev, "%B %d,%Y"),
strptime = strptime(largev, "%B %d,%Y"),
times = 10
)

Which gives:

#Unit: seconds
# expr min lq mean median uq max neval cld
# as.Date 1.479891 1.480671 1.527838 1.483158 1.489222 1.863777 10 a
# strptime 2.177625 2.183247 2.237732 2.255282 2.268452 2.272537 10 b

As per mentionned by @cory in the comments, use ?strptime to get the format codes:

  • %B Full month name in the current locale. (Also matches abbreviated name on input.)
  • %d Day of the month as decimal number (01–31).
  • %Y Year with century. Note that whereas there was no zero in the original Gregorian calendar, ISO 8601:2004 defines it to be valid (interpreted as 1BC)

Convert character to Date (Thu Jun 14 *** 2018-05-14) in r

This sure is not the easiest way to do it, But I just wanted you to have a quick answer.

library(stringr)
library(dplyr)
Data=data.frame(date=c("Thu Jun 14","Fri Jun 15","Tue Jun 19","Wed Jun 20"),match_name=c("a","b","c","d"),price=c(1,2,3,4))
Data$date=as.character(Data$date)

regexp <- "[[:digit:]]+"
Data=mutate(Data,datenum=str_extract(Data$date, regexp))
Data=mutate(Data,monthnum=str_extract(Data$date, regexp))

Data=mutate(Data,monthname=str_extract(Data$date,"Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec"))

Data=mutate(Data,monthnum=if(Data$monthname=="Jan")
"01"
else if(Data$monthname=="Feb")
"02"
else if(Data$monthname=="Mar")
"03"
else if(Data$monthname=="Apr")
"04"
else if(Data$monthname=="May")
"05"
else if(Data$monthname=="Jun")
"06"
else if(Data$monthname=="Jul")
"07"
else if(Data$monthname=="Aug")
"08"
else if(Data$monthname=="Sep")
"09"
else if(Data$monthname=="Oct")
"10"
else if(Data$monthname=="Nov")
"11"
else if(Data$monthname=="Dec")
"12"
)
mutate(Data,Final_Date=paste0("2018-",monthnum,"-",datenum))

Resulting in

date match_name price datenum monthnum monthname Final_Date
1 Thu Jun 14 a 1 14 06 Jun 2018-06-14
2 Fri Jun 15 b 2 15 06 Jun 2018-06-15
3 Tue Jun 19 c 3 19 06 Jun 2018-06-19
4 Wed Jun 20 d 4 20 06 Jun 2018-06-20

How to convert variable with mixed date formats to one format?

You may try parse_date_time in package lubridate which "allows the user to specify several format-orders to handle heterogeneous date-time character representations" using the orders argument. Something like...

library(lubridate)
parse_date_time(x = df$date,
orders = c("d m y", "d B Y", "m/d/y"),
locale = "eng")

...should be able to handle most of your formats. Please note that b/B formats are locale sensitive.

Other date-time formats which can be used in orders are listed in the Details section in ?strptime.

Converting year and month (yyyy-mm format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02 310
2009-03 2379
2009-04 234
2009-05 14
2009-08 1
2009-09 34
2009-10 2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009
12 310 2379 234 14 1 34 2386

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

Parsing a string to a date in JavaScript

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),

to display a date in user's local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method - use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

Parse date string and change format

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>

How to convert String to Date without knowing the format?

You cant!

If you have the date 2010-08-05 then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.

Format date strings comprising weeks and quarters as Date objects

I dont know of any specific function, but here's a basic one:

convert_WQ_to_Date <- function(D) {
weeks <- as.integer(substr(D, 3, 4))
quarter <- as.integer(substr(D, 6, 6))
year <- substr(D, 7, 10)

days <- 7 * ((quarter - 1) * 13 + (weeks-1))
as.Date(sprintf("%s-01-01", year)) + days
}

Example

D <- c("WK01Q32014", "WK01Q12014", "WK05Q42014", "WK01Q22014", "WK02Q32014")

convert_WQ_to_Date(D)
[1] "2014-07-02" "2014-01-01" "2014-10-29" "2014-04-02" "2014-07-09"


Related Topics



Leave a reply



Submit