【问题标题】:For loop dates without losing date format [duplicate]对于不丢失日期格式的循环日期[重复]
【发布时间】:2018-06-09 01:07:37
【问题描述】:

我正在尝试使用 for 循环从 R 中的 SQL 查询中提取日期。目前我有:

StartDate<-"2017-07-01"
EndDate<- "2017-07-05"
dates<-seq(as.POSIXct(StartDate, format="%Y-%m-%d"), as.POSIXct(EndDate, format="%Y-%m-%d"), by='days')

for (f in dates){
. 
. Code here that is inside for loop
.
}

我的问题是它不像 Dates 那样以日期格式出现。如何获得与 StartDate 和 EndDate 格式相同的 f?

【问题讨论】:

  • 你就不能:for (f in as.character(dates)) {}吗?
  • for 循环中尝试使用as.list 包装日期

标签: r date for-loop format


【解决方案1】:

让我们尝试as.list() 包装器,以便在for 循环中保留“日期”格式

for (f in as.list(dates)){
 print(str(f))
}

【讨论】:

  • 这比我做的更好,但由于某种原因,它在循环中跳过了我的一半代码?不确定为什么......也许这是我的代码?可以进入 for 循环的内容是否有限制?
  • 我不认为for 循环有任何迭代限制。
【解决方案2】:
StartDate<-"2017-07-01"
EndDate<- "2017-07-05"
dates<-seq(as.POSIXct(StartDate, format="%Y-%m-%d"), as.POSIXct(EndDate, format="%Y-%m-%d"), by='days')

for (f in dates){
print(as.POSIXct(f,origin = "1970-01-01"))
}   

【讨论】:

猜你喜欢
  • 2022-11-23
  • 2015-07-09
  • 2015-05-21
  • 1970-01-01
  • 2021-06-20
  • 2019-11-20
  • 2015-08-18
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多