How do I convert the y%m%d%H
format into "%Y%m%d %H:%M:%S"
. My dates run from 1970 to 2010.

- 59,189
- 14
- 150
- 185

- 95
- 1
- 3
- 6
-
1date <- strptime(Z$V1,format = "%y%m%d%H",tz = "GMT") – user1537175 Jul 23 '12 at 14:18
-
1What you suggested above seems to work for me: as a tiny example (hint, see http://tinyurl.com/reproducible-000): `strptime("2012 5 10 13",format="%Y %m %d %H")` gives `[1] "2012-05-10 13:00:00"` – Ben Bolker Jul 23 '12 at 14:23
-
%Y%m%d%H with this format it works but format is %y%m%d%H example 00010100(2000010100) – user1537175 Jul 23 '12 at 14:32
2 Answers
Going partly from the comments (it would be nice if you could modify the question accordingly), it seems that this is not a case of formatting (%y
vs %Y
or spacing/delimiters), but of strptime
/POSIX*t
automatically setting the format to skip the hours/minutes/seconds when a 'midnight' time is specified. (This is my current guess based on the following examples, but I could have missed something.)
with %y
, with non-midnight time:
> str(strptime("00020304",format="%y%m%d%H"))
POSIXlt[1:1], format: "2000-02-03 04:00:00"
ditto, midnight time:
> str(strptime("00020300",format="%y%m%d%H"))
POSIXlt[1:1], format: "2000-02-03"
midnight time (with spaces)
> str(strptime("00 02 03 00",format="%y %m %d %H"))
POSIXlt[1:1], format: "2000-02-03"
a vector with one midnight and one non-midnight time:
> str(strptime(c("00020300","00020304"),format="%y%m%d%H"))
POSIXlt[1:2], format: "2000-02-03 00:00:00" "2000-02-03 04:00:00"
So it looks like Dirk's answer is the way to go.

- 211,554
- 25
- 370
- 453
Try this:
R> Sys.Date()
[1] "2012-07-23"
R> format(Sys.Date())
[1] "2012-07-23"
R> format(Sys.Date(), "%Y-%m-%d %H:%M:%S")
[1] "2012-07-23 00:00:00"
R>
as you probably have a Date
type which, by definition, has no hour/minute/second information--use POSIXct
for that. See help(DateTimeClasses)
the details, and a bazillion posts here and on the various mailing lists with working examples.

- 360,940
- 56
- 644
- 725
-
%Y%m%d%H with this format it works but format is %y%m%d%H example 00010100(2000010100) – user1537175 Jul 23 '12 at 14:32
-
Based on my tests below it's not quite that the OP has a `Date` type, but rather than `POSIX*t` seems to set the format to skip H/M/S when it has a date at a midnight time. – Ben Bolker Jul 23 '12 at 15:21
-
That is possible too, but as he never told us via a reproducible example, we cannot really tell, can we? – Dirk Eddelbuettel Jul 23 '12 at 15:24
-
There are examples in the comments (if that counts). To the OP's credit (although it's not a well-written question), the fact that (it seems) `POSIX*t` sets a different format for vectors with all-midnight and some-non-midnight times is potentially confusing (and again IMHO) not a great default choice of behavior. – Ben Bolker Jul 23 '12 at 15:46