美文网首页
【每天一个R语言命令】-strptime/strftime

【每天一个R语言命令】-strptime/strftime

作者: 肖ano | 来源:发表于2021-01-31 12:41 被阅读0次

    【准备】
    R中有专门的时间格式数据,ts(time series)。
    比如:

    > class(presidents)
    [1] "ts"
    > class(airmiles)
    [1] "ts"
    

    【描述】

    The strptime function converts characters to time objects.
    The strftime function converts time objects to characters.
    【用法】
    strptime(x, format=', tz='', ...)
    【参数】
    x代表字符,format代表格式,tz代表time zone
    【代码】

    > Sys.time()
    [1] "2021-01-31 11:42:31 CST" #sct也就是中国的时间
    
    > time_1 <- "2021-01-31"   
    > class(time_1)
    [1] "character"
    
    > time_2 <- strptime(time_1, format = '%Y-%m-%d')
    > class(time_2)
    [1] "POSIXlt" "POSIXt"
    
    time_3 <- "2020-06-01 16:15:10"
    > time_3a <- strptime(time_3,                              # Apply strptime with timezone
    +                     format = "%Y-%m-%d %H:%M:%OS",
    +                     tz = "") #当前时区省略不写
    > time_3a
    [1] "2020-06-01 16:15:10 CST"
    
    # 生成日期
    > seq(as.Date('2020-02-01'),as.Date('2020-02-10'), by=1)
     [1] "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" "2020-02-05" "2020-02-06" "2020-02-07" "2020-02-08"
     [9] "2020-02-09" "2020-02-10"
    # 生成时间序列
    > sales <- round(runif(20, min = 50, max = 100))
    > ts(sales, start = c(2000,1), end = c(2020,12), frequency = 1)
    Time Series:
    Start = 2000 
    End = 2031 
    Frequency = 1 
     [1] 56 53 85 82 77 88 76 81 80 67 92 97 76 82 68 55 78 72 69 73 56 53 85 82 77 88 76 81 80 67 92 97
    

    相关文章

      网友评论

          本文标题:【每天一个R语言命令】-strptime/strftime

          本文链接:https://www.haomeiwen.com/subject/hmaqtltx.html