【问题标题】:How to unify date format from HTML timestamps如何从 HTML 时间戳中统一日期格式
【发布时间】:2021-10-20 20:46:40
【问题描述】:

我正在使用 python 脚本从许多出版商的网站上抓取文章的发布日期。此数据可在 HTML 属性或标签中找到,这些属性或标签以“时间”、“时间戳”和“发布日期”等各种方式标识,并以例如以下格式提供时间:

<time class="timestamp article__timestamp flexbox__flex--1"> Updated Aug. 18, 2021 3:54 pm ET </time>

<time class="css-x7rtpa e16638kd0" datetime="2021-08-18T19:10:54-04:00">Aug. 18, 2021</time>

<time datetime="2021-08-18T15:45:33-04:00"><span class="date">August 18, 2021</span><span class="time">3:45 PM ET</span></time>

<div class="timestamp"><span aria-label="Published on August 19, 2021 12:36 AM ET" class="timestamp__date--published"><span aria-hidden="true">08/19/2021 12:36 am ET</span></span></div>

<div class="article-date"><strong>Published</strong> <time> 8 hours ago</time></div>

'published_time': '2021-08-18T05:33:59Z

这就是我从那些 HTML 标记中获取这些日期的文本后通常的样子:

Aug. 18, 2021 6:56 am ET

Aug. 18, 2021

Updated Aug. 18, 2021 3:54 pm ET

Published 6 hours ago

2021-08-18T08:00:00Z

我计划在未来抓取更多出版商的网站,所以在我编写自己的脚本之前,我很好奇是否存在统一这种格式的现有解决方案或框架。

上面的标签和生成的文本没有以 1:1 的关系显示,因为有足够的变化,以至于除了编写我自己的脚本之外,这对于解决方案来说有点无关紧要。到目前为止,我发现的解决方案引用了 Javascript 中的统一日期,但在从 HTML 标记中提取时却没有。

这些日期最终将由用 Swift 编写的服务器应用程序使用。

【问题讨论】:

  • datetime.strptime 将能够处理其中的一些但不是全部。没有通用的解决方案。您将不得不编写代码来识别字符串中的内容并进行适当处理

标签: python html date beautifulsoup tags


【解决方案1】:

dateparser python 库看起来是满足我需求的最佳解决方案。

  • 支持几乎所有现有的日期格式:绝对日期、相对日期(“两周前”或“明天”)、时间戳等。
  • 支持 200 多种语言区域。
  • 语言自动检测。
  • 可通过设置自定义行为。
  • 支持非公历系统。
  • 支持带有时区缩写或 UTC 偏移量的日期(“2015 年 8 月 14 日 EST”、“2013 年 7 月 21 日 10:15 pm +0500”...) 在较长的文本中搜索日期。

为了长期稳定,生产部署始终需要考虑:

  • 积极支持
  • 超过 7.4k 用户
  • 90 多名贡献者

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2020-10-05
    • 2018-06-15
    • 2022-01-24
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2016-02-13
    • 2012-01-03
    相关资源
    最近更新 更多