R语言 从生产报表里时间分段判断班组班次
Posted 基督徒Isaac
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R语言 从生产报表里时间分段判断班组班次相关的知识,希望对你有一定的参考价值。
# 生产报表----
library(RODBC)
library(tidyverse)
library(lubridate) # 转化时区 force_tz() tzone='asia/shanghai'
library(anytime) # 获取日期 anydate() 时区CST
library(hms) # 获取时间 :as_hms()
myconn <-odbcConnect(
"HBS",
uid = "HfM",
pwd = "***r"
)
jitai <- sqlFetch(
channel = myconn,
sqtable = "tblHZJOps"
)
# 或
# sqlQuery(
# channel = myconn,
# query =
# "select * from tblHZJOps
# where StartTime >= '2000-1-1'") # 存在时间截取不全的问题
jitai$StartTime[1] # 时区 CST, 与anytime::anydate()输出结果时区一致
yiyue <- jitai %>% filter(StartTime >= as.Date("2022-1-1"))
yiyue$StartTime[1] # cst 七点四十五之前
yiyue <- jitai %>% filter(StartTime >= anytime::anytime("2022-1-1 07:45:00")) # cst
yiyue$StartTime[1] # cst 七点四十五之后
# 时间分段----
baiye <-
function(x = lubridate::ymd_hms("2021.12.31 0:0:0"))
origin <- hms::as_hms("07:45:00")
TimeStamp = c()
for (i in 1:NROW(x))
StartTime <- lubridate::force_tz(x[i], tzone='asia/shanghai')
date <- anytime::anydate(StartTime)
time <- hms::as_hms(StartTime)
hour <- (time - origin) / 3600
if (hour >= 0 & hour < 12)
stamp <- hms::as_hms("07:45:00")
TimeStamp[i] <- paste(date, stamp); TimeStamp[i]
else if (hour >= 12)
stamp <- hms::as_hms("19:45:00")
TimeStamp[i] <- paste(date, stamp); TimeStamp[i]
else if (hour < 0)
stamp <- hms::as_hms("19:45:00")
TimeStamp[i] <- paste(date - 1 , stamp); TimeStamp[i]
else
stamp <- ""
TimeStamp[i] <- ""
# 字符向量,需转化为时间
y <- lubridate::force_tz(lubridate::ymd_hms(TimeStamp),
tzone='asia/shanghai')
return(y)
lubridate::ymd_hms("2021.12.31 0:0:0") # UTC
anytime::anydate(ymd_hms("2021.12.31 0:0:0")) # 日期
hms::as_hms(ymd_hms("2021.12.31 0:0:0")) # 无时区区别 所以无所谓转化时区
baiye()
yiyue$StartTime[1]
baiye(yiyue$StartTime[1])
yiyue <- yiyue %>% mutate(
TimeStamp = StartTime %>% baiye()
)
# 判断班组(基于时间分段的基础)----
panduan <-
function(X = lubridate::force_tz(lubridate::ymd_hms("2021.12.31 7:45:0"),
tzone='asia/shanghai'))
a = lubridate::force_tz(lubridate::ymd_hms("2021.12.31 7:45:0"),
tzone='asia/shanghai')
b = 1/2
d = c()
for (i in 1:NROW(X))
x = X[i]
c = as.numeric((x - a) / b) %% 12
if (c %in% c(0,2,5,7))
d[i] <- "甲"
else if (c %in% c(8,10,1,3))
d[i] <- "乙"
else if (c %in% c(4,6,9,11))
d[i] <- "丙"
else
d[i] <- ""
return(d)
panduan()
yiyue$TimeStamp[1]
panduan(lubridate::force_tz(yiyue$TimeStamp[1]))
yiyue <- yiyue %>% mutate(
banzu = TimeStamp %>% panduan()
)
# 判断班次----
baiye1 <- function(x = hms::as_hms("07:45:0"))
y = c()
for (i in 1:NROW(x))
a = hms::as_hms(x[i])
if (a == hms::as_hms("07:45:0"))
y[i] = "白班"
else if (a == hms::as_hms("19:45:0"))
y[i] = "夜班"
else
y[i] = ""
return(y)
yiyue <- yiyue %>% mutate(
banci = TimeStamp %>% baiye1()
)
以上是关于R语言 从生产报表里时间分段判断班组班次的主要内容,如果未能解决你的问题,请参考以下文章
如何在 R 中为日期添加时间(午夜)并在没有 1 或 2 小时班次的情况下打印它?