【问题标题】:Loop through dates Mac OSX Terminal Bash循环遍历日期 Mac OSX Terminal Bash
【发布时间】:2020-09-14 12:15:54
【问题描述】:

我希望从终端 (Mac OSX) 执行 python 脚本。 python 脚本需要两个日期(开始日期和结束日期)。这两个参数需要相隔一天。我在终端运行的当前代码如下:

#!/bin/bash

# Set beg date
beg= 2012-01-01

# Set a counter variable
counter=1 

# Increase the counter to get back in time
while [ "$beg" != 2020-08-01 ]; do
  echo $beg
  beg=$(beg -v -${counter}d '+%Y-%m-%d')
  end=$(beg -v -${((counter+1))}d '+%Y-%m-%d')
  python fetch_links.py beg end
  counter=$((counter + 1))
done

我收到了下面列出的几个错误:

fetch_links.py: error: argument date_start: end is not a proper date string

-bash: beg: command not found
-bash: -${((counter+1))}d: bad substitution

我的目标是从开始日期 (2012-01-01) 开始,将开始日期和结束日期传递给 python 脚本,直到 2012 年到今天之间的所有每日时段都已过去。例如,第一次迭代应该通过“2012-01-01”作为开始日期和“2012-01-02”作为结束日期。

【问题讨论】:

  • beg= ... 出现错误,var、= 和值之间不应有空格。
  • @arhodes4 : $(beg -v ....) 调用名为 beg 的命令。您的 PATH 中似乎没有此名称的可执行文件。除此之外,用 Python 完成整个日期算术不是更容易吗?
  • @arhodes4 : ${((counter+1))} 也没有意义。你的意思是$((counter+1)) 吗?

标签: bash macos terminal


【解决方案1】:

解决方法如下:

startdate=2012-01-01
end=2020-08-01
enddate=2012-01-02

sDateTs=`date -j -f "%Y-%m-%d" $startdate "+%s"`
eDateTs=`date -j -f "%Y-%m-%d" $enddate "+%s"`
e1DateTs=`date -j -f "%Y-%m-%d" $end "+%s"`
dateTs=$sDateTs
date1Ts=$eDateTs
offset=86400

while [ "$dateTs" -le "$e1DateTs" ]
do
  date1=`date -j -f "%s" $dateTs "+%Y-%m-%d"`
  date2=`date -j -f "%s" $date1Ts "+%Y-%m-%d"`  
  python fetch_links.py $date1 $date2
  dateTs=$(($dateTs+$offset))
  date1Ts=$(($date1Ts+$offset))
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    相关资源
    最近更新 更多