Welcome, guest | Sign In | My Account | Store | Cart

I wrote this little function for `[Gate One](http://vimeo.com/24857127)` (a web-based terminal emulator/SSH client)... It converts strings in the format of <num><character> into timedelta objects. It's not rocket science but maybe it'll save someone a few keystrokes :). Besides that, it comes with a really nice Sphinx-ready (reStructuredText) docstring with complete doctests.

Python, 41 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41``` ```from datetime import timedelta def convert_to_timedelta(time_val): """ Given a *time_val* (string) such as '5d', returns a timedelta object representing the given value (e.g. timedelta(days=5)). Accepts the following '' formats: ========= ======= =================== Character Meaning Example ========= ======= =================== s Seconds '60s' -> 60 Seconds m Minutes '5m' -> 5 Minutes h Hours '24h' -> 24 Hours d Days '7d' -> 7 Days ========= ======= =================== Examples:: >>> convert_to_timedelta('7d') datetime.timedelta(7) >>> convert_to_timedelta('24h') datetime.timedelta(1) >>> convert_to_timedelta('60m') datetime.timedelta(0, 3600) >>> convert_to_timedelta('120s') datetime.timedelta(0, 120) """ num = int(time_val[:-1]) if time_val.endswith('s'): return timedelta(seconds=num) elif time_val.endswith('m'): return timedelta(minutes=num) elif time_val.endswith('h'): return timedelta(hours=num) elif time_val.endswith('d'): return timedelta(days=num) if __name__ == "__main__": import doctest doctest.testmod() ```
 Created by Dan McDougall on Thu, 6 Oct 2011 (Apache)

### Required Modules

• (none specified)