简体   繁体   English

从xlsx文件加载数据作为日期和时间

[英]load data from xlsx file as date and time

Now a xlsx file contained a date column as : 现在,xlsx文件包含一个日期列,如下所示:

Date
2019-3-1 0:15
2019-3-1 19:15
2019-3-1 23:15

How can I load it into data.frame as read date and time datatype? 如何将其作为读取日期和时间数据类型加载到data.frame中? My tool is openxlsx package and I tried like: 我的工具是openxlsx包,我尝试过:

df <- readWorkbook(xlsxFile = '0301-0314.xlsx',sheet=1)

First you read the data set using any library. 首先,您可以使用任何库读取数据集。 Then you can try as.POSIXlt or as.POSIXct to define the date-time format. 然后,您可以尝试使用as.POSIXltas.POSIXct定义日期时间格式。 This also allows you to provide timezone info along with date-time format. 这还允许您提供时区信息以及日期时间格式。 Example: 例:

> sampledf <- data.frame(DateTime = c("2019-3-1 0:15",
+                            "2019-3-1 19:15",
+                            "2019-3-1 23:15")
+ )
> str(sampledf$DateTime)
 Factor w/ 3 levels "2019-3-1 0:15",..: 1 2 3
> sampledf$DateTime <- as.POSIXlt(sampledf$DateTime ,"GMT",format = "%Y-%m-%d %H:%M")
> str(sampledf$DateTime)
 POSIXlt[1:3], format: "2019-03-01 00:15:00" "2019-03-01 19:15:00" ...

Timezone info "GMT" can be replace with any time zone. 时区信息“ GMT”可以替换为任何时区。 More about different time formatting options in R is available here. 有关R中不同时间格式选项的更多信息,请参见此处。

This will work: 这将起作用:

# Create example dataset:
df <- data.frame(Date = c("2019-3-1 0:15",
                        "2019-3-1 19:15",
                        "2019-3-1 23:15")
                )
df$Date <- as.character(df$Date)
# Format "Date" as date and time:
df$time <- strptime(as.character(df$Date), "%Y-%m-%d %H:%M")
# Check:
str(df)
# If then you would like to count time, for example in number of hours, from a certain initial time (e.g. 2019-3-1 0:15) try:
df$timestep <- as.numeric(difftime(time2="2019-3-1 0:15", time1=df$time, units="hours"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM