【问题标题】:Relative Date Base with Dateutil使用 Dateutil 的相对日期基准
【发布时间】:2015-01-22 00:34:58
【问题描述】:

我正在尝试使用 dateutil.parse 使用 Python 解析相对日期(今天 4:00、明天 10:00、昨天 8:00 等),但我想提供一个“今天”日期实际用作基础。问题是我可能正在查看昨天创建的内容,但其内容中仍有“今天”,因此 dateutil.parse 不会解析出真正的 DateTime。

有什么解决方法吗?

【问题讨论】:

    标签: python date python-dateutil


    【解决方案1】:

    dateutil.parser.parse() function has default parameter 但它不解析相对人类可读的日期。您可以为此使用parsedatetime module

    #!/usr/bin/env python
    from datetime import datetime
    import parsedatetime # $ pip install parsedatetime
    
    today = datetime(2015, 1, 1)
    calendar= parsedatetime.Calendar()
    for timestring in [
            "today at 4:00", 
            "tomorrow at 10:00", 
            "yesterday at 8:00"]:
        d, parsed_as = calendar.parseDT(timestring, today)
        assert parsed_as == 3 # as datetime
        print(d)
    

    输出

    2015-01-01 04:00:00
    2015-01-02 10:00:00
    2014-12-31 08:00:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多