2

I have a year list (format date) and I would to transform this year into a %Y%m%d %H:%M:%S format and the month must be 01 and day must be 01 as in the example below :

1800 transformed in 1800/01/01 00:00:00

Anybody as a solution ?

zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

3

Try zoo library:

library(zoo)
> (date <- as.POSIXct(as.yearmon(2010)))
[1] "2010-01-01 GMT"
> format(date, "%Y/%m/%d %H:%M:%S")
[1] "2010/01/01 00:00:00"

EDIT: @user3370470 Please explain yourself. The below confirm what I've been saying so far.

> format(as.POSIXct(as.yearmon(1800)), "%Y/%m/%d %H:%M:%S")
[1] "1800/01/01 00:00:00"
> format(as.yearmon(1800), "%Y/%m/%d %H:%M:%S")
[1] "1800/01/01 00:00:00"

The result of as.POSIXct(as.yearmon(1800) is a datetime object, class POSIXct.

Michele
  • 8,563
  • 6
  • 45
  • 72
  • Thanks for the answer. But this not function well because I have %H:%M:%S not in a 00:00:00 format. The Gavin Kelly's answer is very good. – user3370470 Mar 25 '14 at 10:12
  • @user3370470 I don't understand the above result is exactly as you asked... please clarify – Michele Mar 25 '14 at 10:13
  • @user3370470 Have you figured why `%H:%M:%S not in a 00:00:00 format` ? I still don't see the different between the above method and your requirements... – Michele Mar 25 '14 at 10:36
  • 3
    This answer does correctly transform 1800 to 1800/01/01 00:00:00 which appears to be the question you asked. If that is not what you intended please read http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and improve the question accordingly. – G. Grothendieck Mar 25 '14 at 11:10
  • In fact I have a date type respond like : 1800/01/01 00:09:21 or 1800/01/01 01:00:00 for all my data. But I want to deduct this date list from an other date list and it's important for me to have strictly a date format : 1800/01/01 00:00:00. May be a problem with the type of my date ? I don't know ... For me, the Gavin Kelly's command return all the date format 1800/01/01 00:00:00. – user3370470 Mar 25 '14 at 18:27
1

I don't know of a date format - there's a Date class, do you mean that. If the only info you have is the year, then why not sprintf("%s/01/01 00:00:00", charYear) where charYear is a vector of string representations of the year.

Gavin Kelly
  • 2,374
  • 1
  • 10
  • 13
  • Nice, and you can easily wrap the above like : `as.POSIXct(sprintf("%s/01/01 00:00:00", 2010))` and get an actual datetime class, cause it is in the default format. – Michele Mar 25 '14 at 10:04