【问题标题】:Subtract or add time to web-scraped times减去或增加网络抓取时间的时间
【发布时间】:2014-03-24 15:07:12
【问题描述】:

我正在为自己编写一个一次性脚本,以获取周五和周六的日落时间,以确定安息日和哈夫达拉的开始时间。现在,我可以使用 BeautifulSoup 从 timeanddate.com 上抓取时间,并将它们存储在一个列表中。不幸的是,我被那些时代困住了。我想做的是能够减少或增加他们的时间。由于安息日烛光时间是日落前 18 分钟,我希望能够将周五的给定日落时间减去 18 分钟。这是我到目前为止的代码:

import datetime
import requests
from BeautifulSoup import BeautifulSoup

# declare all the things here...
day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year
soup = BeautifulSoup(requests.get('http://www.timeanddate.com/worldclock/astronomy.html?n=43').text)
# worry not. 
times = []

for row in soup('table',{'class':'spad'})[0].tbody('tr'):
    tds = row('td')
    times.append(tds[1].string)
#end for

shabbat_sunset = times[0]
havdalah_time = times[1]

到目前为止,我被困住了。 times[] 中的对象显示为 BeautifulSoup NavigatableStrings,我无法将其修改为整数(原因很明显)。任何帮助将不胜感激,非常感谢你。

编辑 所以,我使用了使用 mktime 的建议,将 BeautifulSoup 的字符串变成了常规字符串。现在我得到一个 OverflowError: mktime out of range when I call mktime on shabbat...

for row in soup('table',{'class':'spad'})[0].tbody('tr'):
    tds = row('td')
    sunsetStr = "%s" % tds[2].text
    sunsetTime = strptime(sunsetStr,"%H:%M")
    shabbat = mktime(sunsetTime)
    candlelighting = mktime(sunsetTime) - 18 * 60
    havdalah = mktime(sunsetTime) + delta * 60

【问题讨论】:

  • mktime 返回其参数与 1970 年 1 月 1 日之间的秒数。您没有提供足够的信息。从 1970 年 1 月 1 日到下午 5:30 之间有多少秒?

标签: python time


【解决方案1】:

我采取的方法是将完整时间解析为正常表示 - 在 Python 世界中,此表示是自 Unix 纪元(1970 年 1 月 1 日午夜)以来的秒数。为此,您还需要查看第 0 列。(顺便说一下,tds[1] 是日出时间,而不是我认为您想要的时间。)

见下文:

#!/usr/bin/env python
import requests
from BeautifulSoup import BeautifulSoup
from time import mktime, strptime, asctime, localtime

soup = BeautifulSoup(requests.get('http://www.timeanddate.com/worldclock/astronomy.html?n=43').text)
# worry not. 

(shabbat, havdalah) = (None, None)

for row in soup('table',{'class':'spad'})[0].tbody('tr'):
    tds = row('td')
    sunsetStr = "%s %s" % (tds[0].text, tds[2].text)
    sunsetTime = strptime(sunsetStr, "%b %d, %Y %I:%M %p")
    if sunsetTime.tm_wday == 4: # Friday
        shabbat = mktime(sunsetTime) - 18 * 60
    elif sunsetTime.tm_wday == 5: # Saturday
        havdalah = mktime(sunsetTime)

print "Shabbat - 18 Minutes: %s" % asctime(localtime(shabbat))
print "Havdalah              %s" % asctime(localtime(havdalah))

第二,帮助自己:“tds”列表是 BeautifulSoup.Tag 的列表。要获取有关此对象的文档,请打开 Python 终端,键入

import BeautifulSoup help(BeautifulSoup.Tag)

【讨论】:

    【解决方案2】:

    您应该使用 datetime.timedelta() 函数。

    例如:

    time_you_want = datetime.datetime.now() + datetime.timedelta(分钟 = 18)

    另见此处:

    Python Create unix timestamp five minutes in the future

    沙洛姆安息日

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多