Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 来自BeautifulSoup4 Webscrape的时区与原始来源不同_Python_Web Scraping_Beautifulsoup_Google Calendar Api_Timezone Offset - Fatal编程技术网

Python 来自BeautifulSoup4 Webscrape的时区与原始来源不同

Python 来自BeautifulSoup4 Webscrape的时区与原始来源不同,python,web-scraping,beautifulsoup,google-calendar-api,timezone-offset,Python,Web Scraping,Beautifulsoup,Google Calendar Api,Timezone Offset,我正在使用beautifulsoup4从谷歌日历中获取信息。我生成了一个包含日期的列表,后面是有约会的人的姓名,以及会议发生的时间。然而,出于某种原因,web scrape生成的时间提前了5个小时,我不知道为什么 以下是我用来生成列表的内容: 导入请求 进口稀土 从bs4导入BeautifulSoup url=https://calendar.google.com/calendar/htmlembed?src=stationhouston.com_rjtfsabha07jarsumdg7v95

我正在使用beautifulsoup4从谷歌日历中获取信息。我生成了一个包含日期的列表,后面是有约会的人的姓名,以及会议发生的时间。然而,出于某种原因,web scrape生成的时间提前了5个小时,我不知道为什么

以下是我用来生成列表的内容:

导入请求 进口稀土 从bs4导入BeautifulSoup url=https://calendar.google.com/calendar/htmlembed?src=stationhouston.com_rjtfsabha07jarsumdg7v95b10@group.calendar.google.com&&mode=议程 r=requests.geturl 汤=美丽的汤 soup2=soup.find_alldiv,{class:date section} 对于soup2中的项目:
print item.text谷歌日历无法获取任何时区信息,因为您没有使用浏览器。代替特定时区,它将始终默认为UTC

有点痛,但你可以这样做:

from datetime import datetime
from dateutil import tz
import requests
import re
from bs4 import BeautifulSoup
from dateutil.parser import parse


def convert_time(x):
    from_zone = tz.gettz('UTC')
    to_zone = tz.gettz('America/New_York')
    utc = x.replace(tzinfo=from_zone)
    central = x.astimezone(to_zone)
    return central 

url = "https://calendar.google.com/calendar/htmlembed?src=stationhouston.com_rjtfsabha07jarsumdg7v95b10@group.calendar.google.com&amp&mode=AGENDA"
r = requests.get(url)
soup = BeautifulSoup(r.content)
soup2 = soup.find_all("div", {"class":"date-section"})
for item in soup2:
    try:
        time_str = re.search('[0-9]:[0-9][0-9]', item.text).group(0)
        print("Old time was: {}".format(time_str))
        time_parsed = parse(time_str)
        res = convert_time(time_parsed)
        new_time = '{}:{}'.format(res.hour, res.minute)
        print("New time is: {}".format(new_time))
    except:
        pass 
这里我们使用正则表达式从字符串中提取时间

我们可以使用datetime.parser工具将该字符串自动转换为Python datetime对象

在此基础上,我们使用上面定义的convert_time函数将UTC时间戳转换为CST时间戳

如您所见,输出似乎正确:

Old time was: 2:30
New time is: 22:30
Old time was: 2:30
New time is: 22:30
Old time was: 6:30
New time is: 2:30
Old time was: 3:30
New time is: 23:30
Old time was: 4:30
New time is: 0:30
Old time was: 7:30