BeautifulSoup: 如何获取 datwtime 格式的 youtube 视频的发布日期时间?

BeautifulSoup: How to get publish datetime of a youtube video in datwtime format?

在我的爬虫的一部分中,我需要抓取 YouTube 视频的日期时间格式的发布时间和日期。我正在使用 bs4,到目前为止,我可以按照 YT GUI 向我们显示的方式获得发布的时间格式,即 "published on 6th may, 2017"。但我无法检索实际的日期时间。我该怎么做?

我的代码:

    video_obj["date_published"] = video_soup.find("strong", attrs={"class": "watch-time-text"}).text
    return video_obj["date_published"] 

输出:

Published on Feb 8, 2020

我想要的方式:

YYYY-MM-DD HH:MM:SS

一旦你得到:

Published on Feb 8, 2020

您可以执行以下操作来删除 "Published on"

date_string = soup_string.strip("Published on")

要以 YYYY-MM-DD HH:MM:SS 的格式获取此文件,您可以使用 python 中的 python-dateutil 库。您可以使用以下方式安装它:

pip install python-dateutil

代码:

from dateutil import parser
formatted_date = parser.parse("Published on Feb 8, 2020", fuzzy=True)

这将以 YYYY-MM-DD 格式输出日期 HH:MM:SS

You can read more about python-dateutil parser here

您可以使用 pythons datetime 来解析字符串并格式化输出。

pubstring = video_obj["date_published"]  # "Published on Feb 8, 2020"
# pubstring[:13] cuts of first 13 chars
dt = datetime.datetime.strptime(pubstring[13:], "%b %d, %Y")
return dt.strftime("%F") # Format as needed