How to convert y%m%d%H format into “%Y%m%d %H:%M:%S” in time series data

后端 未结 2 1466
灰色年华
灰色年华 2021-01-29 15:13

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

相关标签:
2条回答
  • 2021-01-29 15:17

    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.

    0 讨论(0)
  • 2021-01-29 15:22

    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.

    0 讨论(0)
提交回复
热议问题