使用strptime()函数将日期转换为R中的时间戳

问题描述 投票:0回答:1

我已将txt文件作为CSV读入R。据我了解,R不会自动将字符串识别为时间戳,因此我需要使用strptime()函数将其从文本值转换为。]

这是我的文本文件的输入:

    29/1/12 19:48
    30/1/12 21:07
    2/2/12 15:53
    3/4/12 0:49
    5/10/12 2:00
    24/10/12 17:11
    14/11/12 3:49
    11/8/13 16:00
    12/7/14 17:00
    31/7/14 8:08
    31/7/14 10:48
    6/8/14 9:24
    16/12/14 3:34
    24/1/15 19:37
    16/6/15 15:55
    16/6/15 19:56
    18/6/15 1:24
    25/6/15 17:20
    26/6/15 18:28
    1/7/15 15:58
    1/7/15 18:05
    2/7/15 18:20
    2/7/15 18:59

我尝试过:

    y <- strptime(timestamp, "%d/%m/%y %H:%M")

但继续获得NA。

有人可以帮我解决这个问题吗?谢谢。

r datetime strptime
1个回答
0
投票
# Make some sample data
timestamp <- c('29/1/12 19:48','30/1/12 21:07','2/2/12 15:53')

# Check that you are dealing characters not factors
str(timestamp)
#chr [1:3] "29/1/12 19:48" "30/1/12 21:07" "2/2/12 15:53"

# Best to specify the time zone when using striptime
strptime(timestamp, "%d/%m/%y %H:%M", tz = 'UTC')
#[1] "2012-01-29 19:48:00 UTC" "2012-01-30 21:07:00 UTC" "2012-02-02 15:53:00 UTC"

# The lubridate package is very useful for working with dates/times
library(lubridate)
lubridate::dmy_hm(timestamp)
#[1] "2012-01-29 19:48:00 UTC" "2012-01-30 21:07:00 UTC" "2012-02-02 15:53:00 UTC"
© www.soinside.com 2019 - 2024. All rights reserved.