Natural time interval processing in Python
Question: I am wondering how to take a user-inputted string (i.e. `1 day, 5 hours, 15
minutes, 2 seconds`) and convert it to either a `timedelta` object or
(preferably) the number of seconds in that interval.

Note that:

  * This is not a question about _[datetime](/questions/tagged/datetime "show questions tagged 'datetime'")s_, it is about **[timedelta](/questions/tagged/timedelta "show questions tagged 'timedelta'")s**. I don’t need “Tomorrow” or “In 5 minutes”, I need “1 day” or “5 minutes.”
  * All fields are optional
  * These are the possible fields: 
    * `year`, `years`, or `y`
    * `month`, `months`, or `m`
    * `week`, `weeks`, or `w`
    * `day`, `days`, or `d`
    * `hour`, `hours`, or `h`
    * `minute`, `minutes`, or `m`
    * `second`, `seconds`, or `s`
  * If you can get me started, I can probably do the rest
  * The input can either be delimited by `,` or whitespace

Thank you!


Answer: You could use [`parsedatetime`
module](https://pypi.python.org/pypi/parsedatetime/):

    
    
    #!/usr/bin/env python
    from datetime import date, datetime
    import parsedatetime as pdt # $ pip install parsedatetime
    
    cal = pdt.Calendar()
    midnight = datetime.fromordinal(date.today().toordinal())
    for s in "1 day, 5 hours, 15 minutes, 2 seconds".split(', '):
        print(repr(cal.parseDT(s, midnight)[0] - midnight))
    

### Output

    
    
    datetime.timedelta(1)
    datetime.timedelta(0, 18000)
    datetime.timedelta(0, 900)
    datetime.timedelta(0, 2)
    

To get number of seconds, call `.total_seconds()` or if you don't need
fractions of a second; you could truncate it:

    
    
    integer_seconds = td // timedelta(seconds=1)
    

