Search code examples
pythondatepython-dateutil

Relative Date Base with Dateutil


I'm trying to parse relative dates (today at 4:00, tomorrow at 10:00, yesterday at 8:00, etc.) with Python using dateutil.parse but would like to supply a "today" date to actually use as a base. The issue is I might be looking at content created yesterday but still has "today" in its content, so dateutil.parse doesn't parse out the true DateTime.

Is there any workaround for this?


Solution

  • dateutil.parser.parse() function has default parameter but it doesn't parse relative human-readable dates. You could use parsedatetime module for that:

    #!/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)
    

    Output

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