POSIX formatted Date and Time

依然范特西╮ 提交于 2019-12-20 07:37:57

问题


I am reading this from csv file into R

df <-

ID   DATE         TIME
1    10/14/2000    8:30:05
2    02/13/2001    12:05:05

I have trouble converting this to POSIX formatted date and time.

df <-
ID   DATE         TIME        DATETIMEPOSIX
1    10/14/2000    8:30:05    2000-10-14 8:30:05
2    02/13/2001    01:05:05   2001-02-13 13:05:05   

I have tried this but got NAs

df$DateTime <- paste(df$DATE, df$TIME)
df$DateTimePOSIX <- strptime(df$DateTime,  format = "%Y-%m-%d %H:%M:%S")

回答1:


The format argument needs to be the format of what it's reading, not what you want the output to be.

Also, I assume your date component is in the American version of 'mm/dd/yyyy'

Consider

DateTime <- "10/14/2000 8:30:05"

as.POSIXct(DateTime, format = "%m/%d/%Y %H:%M:%S")
"2000-10-14 08:30:05 AEDT"

So you'll want

df$DateTimePOSIX <- as.POSIXct(df$DateTime,  format = "%m/%d/%Y %H:%M:%S")

df
#   ID       DATE     TIME            DateTime       DateTimePOSIX
# 1  1 10/14/2000  8:30:05  10/14/2000 8:30:05 2000-10-14 08:30:05
# 2  2 02/13/2001 12:05:05 02/13/2001 12:05:05 2001-02-13 12:05:05


来源:https://stackoverflow.com/questions/45603485/posix-formatted-date-and-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!