parsedatetime

repository·master·Indexed 20 days ago

https://github.com/bear/parsedatetime

A Python library for parsing human-readable date and time strings into structured Python datetime objects or tuples. It provides a Calendar class with methods like .parse() for time tuples and .parseDT() for timezone-aware datetime objects, with support for PyICU and built-in locale classes.

Tokens
791
Snippets
5
Records
8
Agent score
22%

What's inside parsedatetime

  1. Install parsedatetime via pip

    master

    You can install the parsedatetime library using pip. The current version targets Python 3 (tested with Python 3.9). If you require Python 2.7 compatibility, use the v2.6 release.

    pip install parsedatetime
  2. Parse strings with timezone support using pytz

    master

    To parse a string with specific timezone awareness, use the .parseDT() method. Pass the datetimeString and a tzinfo object (e.g., from the pytz library). This method returns a datetime object and a parse status.

    import parsedatetime
    from pytz import timezone
    
    cal = parsedatetime.Calendar()
    datetime_obj, _ = cal.parseDT(datetimeString="tomorrow", tzinfo=timezone("US/Pacific"))
  3. Basic usage of parsedatetime

    master

    The basic.py example demonstrates the standard workflow for using parsedatetime to parse natural language date/time strings into Python datetime objects. This typically involves initializing a Calendar object and using its parsing methods.

    # Refer to basic.py for the implementation details
    # Typical pattern:
    # from parsedatetime import Calendar
    # cal = Calendar()
    # time_struct, parse_status = cal.parse('tomorrow at 5pm')
  4. Parse human-readable strings as time tuples

    master

    To parse a human-readable string into a time tuple, instantiate a parsedatetime.Calendar() object and use its .parse() method. This returns a tuple representing the time structure and a parse status.

    import parsedatetime
        
    cal = parsedatetime.Calendar()
    time_struct, parse_status = cal.parse("tomorrow")
  5. Parse human-readable strings as Python datetime objects

    master

    To convert a parsed string directly into a standard Python datetime object, use the time tuple returned by cal.parse() and unpack it into the datetime constructor.

    import parsedatetime
    from datetime import datetime
    
    cal = parsedatetime.Calendar()
    time_struct, parse_status = cal.parse("tomorrow")
    # Unpack the first 6 elements of the tuple into datetime
    datetime_obj = datetime(*time_struct[:6])