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

后端 未结 2 1469
灰色年华
灰色年华 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题