



Python Utils 2.7.1 documentation

### Navigation

* [Python Utils 2.7.1 documentation](index.html#document-index) »

Welcome to Python Utils’s documentation![¶](#welcome-to-python-utils-s-documentation "Permalink to this headline")

==================================================================================================================

Contents:

Useful Python Utils[¶](#useful-python-utils "Permalink to this headline")

-------------------------------------------------------------------------

[![https://travis-ci.org/WoLpH/python-utils.svg?branch=master](https://travis-ci.org/WoLpH/python-utils.svg?branch=master)](https://travis-ci.org/WoLpH/python-utils)

[![https://coveralls.io/repos/WoLpH/python-utils/badge.svg?branch=master](https://coveralls.io/repos/WoLpH/python-utils/badge.svg?branch=master)](https://coveralls.io/r/WoLpH/python-utils?branch=master)

Python Utils is a collection of small Python functions and

classes which make common patterns shorter and easier. It is by no means a

complete collection but it has served me quite a bit in the past and I will

keep extending it.

One of the libraries using Python Utils is Django Utils.

Documentation is available at: <https://python-utils.readthedocs.org/en/latest/>

### Links[¶](#links "Permalink to this headline")

> 

> * The source: <https://github.com/WoLpH/python-utils>

> * Project page: <https://pypi.python.org/pypi/python-utils>

> * Reporting bugs: <https://github.com/WoLpH/python-utils/issues>

> * Documentation: <https://python-utils.readthedocs.io/en/latest/>

> * My blog: <https://wol.ph/>

> 

> 

> 

### Requirements for installing:[¶](#requirements-for-installing "Permalink to this headline")

For the Python 3+ release (i.e. v3.0.0 or higher) there are no requirements.

For the Python 2 compatible version (v2.x.x) the six package is needed.

### Installation:[¶](#installation "Permalink to this headline")

The package can be installed through pip (this is the recommended method):

> 

> pip install python-utils

Or if pip is not available, easy\_install should work as well:

> 

> easy\_install python-utils

Or download the latest release from Pypi (<https://pypi.python.org/pypi/python-utils>) or Github.

Note that the releases on Pypi are signed with my GPG key (<https://pgp.mit.edu/pks/lookup?op=vindex&search=0xE81444E9CE1F695D>) and can be checked using GPG:

> 

> gpg –verify python-utils-<version>.tar.gz.asc python-utils-<version>.tar.gz

### Quickstart[¶](#quickstart "Permalink to this headline")

This module makes it easy to execute common tasks in Python scripts such as

converting text to numbers and making sure a string is in unicode or bytes

format.

### Examples[¶](#examples "Permalink to this headline")

To easily retry a block of code with a configurable timeout, you can use the

time.timeout\_generator:

```

>>> for i in time.timeout\_generator(10):

...     try:

...         # Run your code here

...     except Exception as e:

...         # Handle the exception

```

Easy formatting of timestamps and calculating the time since:

```

>>> time.format\_time('1')

'0:00:01'

>>> time.format\_time(1.234)

'0:00:01'

>>> time.format\_time(1)

'0:00:01'

>>> time.format\_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))

'2000-01-02 03:04:05'

>>> time.format\_time(datetime.date(2000, 1, 2))

'2000-01-02'

>>> time.format\_time(datetime.timedelta(seconds=3661))

'1:01:01'

>>> time.format\_time(None)

'--:--:--'

>>> formatters.timesince(now)

'just now'

>>> formatters.timesince(now - datetime.timedelta(seconds=1))

'1 second ago'

>>> formatters.timesince(now - datetime.timedelta(seconds=2))

'2 seconds ago'

>>> formatters.timesince(now - datetime.timedelta(seconds=60))

'1 minute ago'

```

Converting your test from camel-case to underscores:

```

>>> camel\_to\_underscore('SpamEggsAndBacon')

'spam\_eggs\_and\_bacon'

```

A convenient decorator to set function attributes using a decorator:

```

You can use:

>>> @decorators.set\_attributes(short\_description='Name')

... def upper\_case\_name(self, obj):

...     return ("%s %s" % (obj.first\_name, obj.last\_name)).upper()

Instead of:

>>> def upper\_case\_name(obj):

...     return ("%s %s" % (obj.first\_name, obj.last\_name)).upper()

>>> upper\_case\_name.short\_description = 'Name'

```

Or to scale numbers:

```

>>> converters.remap(500, old\_min=0, old\_max=1000, new\_min=0, new\_max=100)

50

# Or with decimals:

>>> remap(decimal.Decimal('250.0'), 0.0, 1000.0, 0.0, 100.0)

Decimal('25.0')

```

To get the screen/window/terminal size in characters:

```

>>> terminal.get\_terminal\_size()

(80, 24)

```

That method supports IPython and Jupyter as well as regular shells, using

blessings and other modules depending on what is available.

To extract a number from nearly every string:

```

>>> converters.to\_int('spam15eggs')

15

>>> converters.to\_int('spam')

0

>>> number = converters.to\_int('spam', default=1)

1

```

To do a global import programmatically you can use the import\_global

function. This effectively emulates a from … import \*

```

from python\_utils.import\_ import import\_global

# The following is the equivalent of `from some\_module import \*`

import\_global('some\_module')

```

Or add a correclty named logger to your classes which can be easily accessed:

```

class MyClass(Logged):

    def \_\_init\_\_(self):

        Logged.\_\_init\_\_(self)

my\_class = MyClass()

# Accessing the logging method:

my\_class.error('error')

# With formatting:

my\_class.error('The logger supports %(formatting)s',

               formatting='named parameters')

# Or to access the actual log function (overwriting the log formatting can

# be done n the log method)

import logging

my\_class.log(logging.ERROR, 'log')

```

python\_utils package[¶](#python-utils-package "Permalink to this headline")

----------------------------------------------------------------------------

### Submodules[¶](#submodules "Permalink to this headline")

### python\_utils.decorators module[¶](#module-python_utils.decorators "Permalink to this headline")

`python_utils.decorators.``set_attributes`(*\*\*kwargs*)[[source]](_modules/python_utils/decorators.html#set_attributes)[¶](#python_utils.decorators.set_attributes "Permalink to this definition")

Decorator to set attributes on functions and classes

A common usage for this pattern is the Django Admin where

functions can get an optional short\_description. To illustrate:

Example from the Django admin using this decorator:

<https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display>

Our simplified version:

```

>>> @set\_attributes(short\_description='Name')

... def upper\_case\_name(self, obj):

...     return ("%s %s" % (obj.first\_name, obj.last\_name)).upper()

```

The standard Django version:

```

>>> def upper\_case\_name(obj):

...     return ("%s %s" % (obj.first\_name, obj.last\_name)).upper()

```

```

>>> upper\_case\_name.short\_description = 'Name'

```

### python\_utils.converters module[¶](#module-python_utils.converters "Permalink to this headline")

`python_utils.converters.``remap`(*value*, *old\_min*, *old\_max*, *new\_min*, *new\_max*)[[source]](_modules/python_utils/converters.html#remap)[¶](#python_utils.converters.remap "Permalink to this definition")

remap a value from one range into another.

```

>>> remap(500, 0, 1000, 0, 100)

50

>>> remap(250.0, 0.0, 1000.0, 0.0, 100.0)

25.0

>>> remap(-75, -100, 0, -1000, 0)

-750

>>> remap(33, 0, 100, -500, 500)

-170

>>> remap(decimal.Decimal('250.0'), 0.0, 1000.0, 0.0, 100.0)

Decimal('25.0')

```

This is a great use case example. Take an AVR that has dB values the

minimum being -80dB and the maximum being 10dB and you want to convert

volume percent to the equilivint in that dB range

```

>>> remap(46.0, 0.0, 100.0, -80.0, 10.0)

-38.6

```

I added using decimal.Decimal so floating point math errors can be avoided.

Here is an example of a floating point math error

>>> 0.1 + 0.1 + 0.1

0.30000000000000004

If floating point remaps need to be done my suggstion is to pass at least

one parameter as a decimal.Decimal. This will ensure that the output

from this function is accurate. I left passing floats for backwards

compatability and there is no conversion done from float to

decimal.Decimal unless one of the passed parameters has a type of

decimal.Decimal. This will ensure that any existing code that uses this

funtion will work exactly how it has in the past.

Some edge cases to test

>>> remap(1, 0, 0, 1, 2)

Traceback (most recent call last):

…

ValueError: Input range (0-0) is empty

```

>>> remap(1, 1, 2, 0, 0)

Traceback (most recent call last):

...

ValueError: Output range (0-0) is empty

```

| Parameters: | * **value** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [*decimal.Decimal*](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)")) – value to be converted

* **old\_min** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [*decimal.Decimal*](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)")) – minimum of the range for the value that has been passed

* **old\_max** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [*decimal.Decimal*](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)")) – maximum of the range for the value that has been passed

* **new\_min** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [*decimal.Decimal*](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)")) – the minimum of the new range

* **new\_max** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [*decimal.Decimal*](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)")) – the maximum of the new range

 |

| Returns: | value that has been re ranged. if any of the parameters passed is

a decimal.Decimal all of the parameters will be converted to

decimal.Decimal. The same thing also happens if one of the

parameters is a float. otherwise all parameters will get converted

into an int. technically you can pass a str of an integer and it

will get converted. The returned value type will be decimal.Decimal

of any of the passed parameters ar decimal.Decimal, the return type

will be float if any of the passed parameters are a float otherwise

the returned type will be int. |

| Return type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)"), [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)"), [decimal.Decimal](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.10)") |

`python_utils.converters.``scale_1024`(*x*, *n\_prefixes*)[[source]](_modules/python_utils/converters.html#scale_1024)[¶](#python_utils.converters.scale_1024 "Permalink to this definition")

Scale a number down to a suitable size, based on powers of 1024.

Returns the scaled number and the power of 1024 used.

Use to format numbers of bytes to KiB, MiB, etc.

```

>>> scale\_1024(310, 3)

(310.0, 0)

>>> scale\_1024(2048, 3)

(2.0, 1)

>>> scale\_1024(0, 2)

(0.0, 0)

>>> scale\_1024(0.5, 2)

(0.5, 0)

>>> scale\_1024(1, 2)

(1.0, 0)

```

`python_utils.converters.``to_float`(*input\_*, *default=0*, *exception=(<type 'exceptions.ValueError'>*, *<type 'exceptions.TypeError'>)*, *regexp=None*)[[source]](_modules/python_utils/converters.html#to_float)[¶](#python_utils.converters.to_float "Permalink to this definition")

Convert the given input\_ to an integer or return default

When trying to convert the exceptions given in the exception parameter

are automatically catched and the default will be returned.

The regexp parameter allows for a regular expression to find the digits

in a string.

When True it will automatically match any digit in the string.

When a (regexp) object (has a search method) is given, that will be used.

WHen a string is given, re.compile will be run over it first

The last group of the regexp will be used as value

```

>>> '%.2f' % to\_float('abc')

'0.00'

>>> '%.2f' % to\_float('1')

'1.00'

>>> '%.2f' % to\_float('abc123.456', regexp=True)

'123.46'

>>> '%.2f' % to\_float('abc123', regexp=True)

'123.00'

>>> '%.2f' % to\_float('abc0.456', regexp=True)

'0.46'

>>> '%.2f' % to\_float('abc123.456', regexp=re.compile(r'(\d+\.\d+)'))

'123.46'

>>> '%.2f' % to\_float('123.456abc', regexp=re.compile(r'(\d+\.\d+)'))

'123.46'

>>> '%.2f' % to\_float('abc123.46abc', regexp=re.compile(r'(\d+\.\d+)'))

'123.46'

>>> '%.2f' % to\_float('abc123abc456', regexp=re.compile(r'(\d+(\.\d+|))'))

'123.00'

>>> '%.2f' % to\_float('abc', regexp=r'(\d+)')

'0.00'

>>> '%.2f' % to\_float('abc123', regexp=r'(\d+)')

'123.00'

>>> '%.2f' % to\_float('123abc', regexp=r'(\d+)')

'123.00'

>>> '%.2f' % to\_float('abc123abc', regexp=r'(\d+)')

'123.00'

>>> '%.2f' % to\_float('abc123abc456', regexp=r'(\d+)')

'123.00'

>>> '%.2f' % to\_float('1234', default=1)

'1234.00'

>>> '%.2f' % to\_float('abc', default=1)

'1.00'

>>> '%.2f' % to\_float('abc', regexp=123)

Traceback (most recent call last):

...

TypeError: unknown argument for regexp parameter

```

`python_utils.converters.``to_int`(*input\_*, *default=0*, *exception=(<type 'exceptions.ValueError'>*, *<type 'exceptions.TypeError'>)*, *regexp=None*)[[source]](_modules/python_utils/converters.html#to_int)[¶](#python_utils.converters.to_int "Permalink to this definition")

Convert the given input to an integer or return default

When trying to convert the exceptions given in the exception parameter

are automatically catched and the default will be returned.

The regexp parameter allows for a regular expression to find the digits

in a string.

When True it will automatically match any digit in the string.

When a (regexp) object (has a search method) is given, that will be used.

WHen a string is given, re.compile will be run over it first

The last group of the regexp will be used as value

```

>>> to\_int('abc')

0

>>> to\_int('1')

1

>>> to\_int('abc123')

0

>>> to\_int('123abc')

0

>>> to\_int('abc123', regexp=True)

123

>>> to\_int('123abc', regexp=True)

123

>>> to\_int('abc123abc', regexp=True)

123

>>> to\_int('abc123abc456', regexp=True)

123

>>> to\_int('abc123', regexp=re.compile(r'(\d+)'))

123

>>> to\_int('123abc', regexp=re.compile(r'(\d+)'))

123

>>> to\_int('abc123abc', regexp=re.compile(r'(\d+)'))

123

>>> to\_int('abc123abc456', regexp=re.compile(r'(\d+)'))

123

>>> to\_int('abc123', regexp=r'(\d+)')

123

>>> to\_int('123abc', regexp=r'(\d+)')

123

>>> to\_int('abc', regexp=r'(\d+)')

0

>>> to\_int('abc123abc', regexp=r'(\d+)')

123

>>> to\_int('abc123abc456', regexp=r'(\d+)')

123

>>> to\_int('1234', default=1)

1234

>>> to\_int('abc', default=1)

1

>>> to\_int('abc', regexp=123)

Traceback (most recent call last):

...

TypeError: unknown argument for regexp parameter: 123

```

`python_utils.converters.``to_str`(*input\_*, *encoding=u'utf-8'*, *errors=u'replace'*)[[source]](_modules/python_utils/converters.html#to_str)[¶](#python_utils.converters.to_str "Permalink to this definition")

Convert objects to string, encodes to the given encoding

| Return type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") |

```

>>> to\_str('a')

b'a'

>>> to\_str(u'a')

b'a'

>>> to\_str(b'a')

b'a'

>>> class Foo(object): \_\_str\_\_ = lambda s: u'a'

>>> to\_str(Foo())

'a'

>>> to\_str(Foo)

"<class 'python\_utils.converters.Foo'>"

```

`python_utils.converters.``to_unicode`(*input\_*, *encoding=u'utf-8'*, *errors=u'replace'*)[[source]](_modules/python_utils/converters.html#to_unicode)[¶](#python_utils.converters.to_unicode "Permalink to this definition")

Convert objects to unicode, if needed decodes string with the given

encoding and errors settings.

| Return type: | unicode |

```

>>> to\_unicode(b'a')

'a'

>>> to\_unicode('a')

'a'

>>> to\_unicode(u'a')

'a'

>>> class Foo(object): \_\_str\_\_ = lambda s: u'a'

>>> to\_unicode(Foo())

'a'

>>> to\_unicode(Foo)

"<class 'python\_utils.converters.Foo'>"

```

### python\_utils.formatters module[¶](#module-python_utils.formatters "Permalink to this headline")

`python_utils.formatters.``camel_to_underscore`(*name*)[[source]](_modules/python_utils/formatters.html#camel_to_underscore)[¶](#python_utils.formatters.camel_to_underscore "Permalink to this definition")

Convert camel case style naming to underscore style naming

If there are existing underscores they will be collapsed with the

to-be-added underscores. Multiple consecutive capital letters will not be

split except for the last one.

```

>>> camel\_to\_underscore('SpamEggsAndBacon')

'spam\_eggs\_and\_bacon'

>>> camel\_to\_underscore('Spam\_and\_bacon')

'spam\_and\_bacon'

>>> camel\_to\_underscore('Spam\_And\_Bacon')

'spam\_and\_bacon'

>>> camel\_to\_underscore('\_\_SpamAndBacon\_\_')

'\_\_spam\_and\_bacon\_\_'

>>> camel\_to\_underscore('\_\_SpamANDBacon\_\_')

'\_\_spam\_and\_bacon\_\_'

```

`python_utils.formatters.``timesince`(*dt*, *default='just now'*)[[source]](_modules/python_utils/formatters.html#timesince)[¶](#python_utils.formatters.timesince "Permalink to this definition")

Returns string representing ‘time since’ e.g.

3 days ago, 5 hours ago etc.

```

>>> now = datetime.datetime.now()

>>> timesince(now)

'just now'

>>> timesince(now - datetime.timedelta(seconds=1))

'1 second ago'

>>> timesince(now - datetime.timedelta(seconds=2))

'2 seconds ago'

>>> timesince(now - datetime.timedelta(seconds=60))

'1 minute ago'

>>> timesince(now - datetime.timedelta(seconds=61))

'1 minute and 1 second ago'

>>> timesince(now - datetime.timedelta(seconds=62))

'1 minute and 2 seconds ago'

>>> timesince(now - datetime.timedelta(seconds=120))

'2 minutes ago'

>>> timesince(now - datetime.timedelta(seconds=121))

'2 minutes and 1 second ago'

>>> timesince(now - datetime.timedelta(seconds=122))

'2 minutes and 2 seconds ago'

>>> timesince(now - datetime.timedelta(seconds=3599))

'59 minutes and 59 seconds ago'

>>> timesince(now - datetime.timedelta(seconds=3600))

'1 hour ago'

>>> timesince(now - datetime.timedelta(seconds=3601))

'1 hour and 1 second ago'

>>> timesince(now - datetime.timedelta(seconds=3602))

'1 hour and 2 seconds ago'

>>> timesince(now - datetime.timedelta(seconds=3660))

'1 hour and 1 minute ago'

>>> timesince(now - datetime.timedelta(seconds=3661))

'1 hour and 1 minute ago'

>>> timesince(now - datetime.timedelta(seconds=3720))

'1 hour and 2 minutes ago'

>>> timesince(now - datetime.timedelta(seconds=3721))

'1 hour and 2 minutes ago'

>>> timesince(datetime.timedelta(seconds=3721))

'1 hour and 2 minutes ago'

```

### python\_utils.import\_ module[¶](#module-python_utils.import_ "Permalink to this headline")

*exception* `python_utils.import_.``DummyException`[[source]](_modules/python_utils/import_.html#DummyException)[¶](#python_utils.import_.DummyException "Permalink to this definition")

Bases: `exceptions.Exception`

`python_utils.import_.``import_global`(*name*, *modules=None*, *exceptions=<class 'python\_utils.import\_.DummyException'>*, *locals\_=None*, *globals\_=None*, *level=-1*)[[source]](_modules/python_utils/import_.html#import_global)[¶](#python_utils.import_.import_global "Permalink to this definition")

Import the requested items into the global scope

WARNING! this method \_will\_ overwrite your global scope

If you have a variable named “path” and you call import\_global(‘sys’)

it will be overwritten with sys.path

Args:

name (str): the name of the module to import, e.g. sys

modules (str): the modules to import, use None for everything

exception (Exception): the exception to catch, e.g. ImportError

locals\_: the locals() method (in case you need a different scope)

globals\_: the globals() method (in case you need a different scope)

level (int): the level to import from, this can be used for

relative imports

### python\_utils.logger module[¶](#module-python_utils.logger "Permalink to this headline")

*class* `python_utils.logger.``Logged`[[source]](_modules/python_utils/logger.html#Logged)[¶](#python_utils.logger.Logged "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.10)")

Class which automatically adds a named logger to your class when

interiting

Adds easy access to debug, info, warning, error, exception and log methods

```

>>> class MyClass(Logged):

...     def \_\_init\_\_(self):

...         Logged.\_\_init\_\_(self)

>>> my\_class = MyClass()

>>> my\_class.debug('debug')

>>> my\_class.info('info')

>>> my\_class.warning('warning')

>>> my\_class.error('error')

>>> my\_class.exception('exception')

>>> my\_class.log(0, 'log')

```

*classmethod* `debug`(*msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.debug "Permalink to this definition")

Log a message with severity ‘DEBUG’ on the root logger.

*classmethod* `error`(*msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.error "Permalink to this definition")

Log a message with severity ‘ERROR’ on the root logger.

*classmethod* `exception`(*msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.exception "Permalink to this definition")

Log a message with severity ‘ERROR’ on the root logger,

with exception information.

*classmethod* `info`(*msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.info "Permalink to this definition")

Log a message with severity ‘INFO’ on the root logger.

*classmethod* `log`(*lvl*, *msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.log "Permalink to this definition")

Log ‘msg % args’ with the integer severity ‘level’ on the root logger.

*classmethod* `warning`(*msg*, *\*args*, *\*\*kwargs*)[¶](#python_utils.logger.Logged.warning "Permalink to this definition")

Log a message with severity ‘WARNING’ on the root logger.

### python\_utils.terminal module[¶](#module-python_utils.terminal "Permalink to this headline")

`python_utils.terminal.``get_terminal_size`()[[source]](_modules/python_utils/terminal.html#get_terminal_size)[¶](#python_utils.terminal.get_terminal_size "Permalink to this definition")

Get the current size of your terminal

Multiple returns are not always a good idea, but in this case it greatly

simplifies the code so I believe it’s justified. It’s not the prettiest

function but that’s never really possible with cross-platform code.

Returns:

width, height: Two integers containing width and height

### python\_utils.time module[¶](#module-python_utils.time "Permalink to this headline")

`python_utils.time.``format_time`(*timestamp*, *precision=datetime.timedelta(0*, *1)*)[[source]](_modules/python_utils/time.html#format_time)[¶](#python_utils.time.format_time "Permalink to this definition")

Formats timedelta/datetime/seconds

```

>>> format\_time('1')

'0:00:01'

>>> format\_time(1.234)

'0:00:01'

>>> format\_time(1)

'0:00:01'

>>> format\_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))

'2000-01-02 03:04:05'

>>> format\_time(datetime.date(2000, 1, 2))

'2000-01-02'

>>> format\_time(datetime.timedelta(seconds=3661))

'1:01:01'

>>> format\_time(None)

'--:--:--'

>>> format\_time(format\_time)  # doctest: +ELLIPSIS

Traceback (most recent call last):

    ...

TypeError: Unknown type ...

```

`python_utils.time.``timedelta_to_seconds`(*delta*)[[source]](_modules/python_utils/time.html#timedelta_to_seconds)[¶](#python_utils.time.timedelta_to_seconds "Permalink to this definition")

Convert a timedelta to seconds with the microseconds as fraction

Note that this method has become largely obsolete with the

timedelta.total\_seconds() method introduced in Python 2.7.

```

>>> from datetime import timedelta

>>> '%d' % timedelta\_to\_seconds(timedelta(days=1))

'86400'

>>> '%d' % timedelta\_to\_seconds(timedelta(seconds=1))

'1'

>>> '%.6f' % timedelta\_to\_seconds(timedelta(seconds=1, microseconds=1))

'1.000001'

>>> '%.6f' % timedelta\_to\_seconds(timedelta(microseconds=1))

'0.000001'

```

`python_utils.time.``timeout_generator`(*timeout*, *interval=datetime.timedelta(0*, *1)*, *iterable=<type 'itertools.count'>*, *interval\_multiplier=1.0*)[[source]](_modules/python_utils/time.html#timeout_generator)[¶](#python_utils.time.timeout_generator "Permalink to this definition")

Generator that walks through the given iterable (a counter by default)

until the timeout is reached with a configurable interval between items

```

>>> for i in timeout\_generator(0.1, 0.06):

...     print(i)

0

1

2

>>> timeout = datetime.timedelta(seconds=0.1)

>>> interval = datetime.timedelta(seconds=0.06)

>>> for i in timeout\_generator(timeout, interval, itertools.count()):

...     print(i)

0

1

2

>>> for i in timeout\_generator(1, interval=0.1, iterable='ab'):

...     print(i)

a

b

```

```

>>> timeout = datetime.timedelta(seconds=0.1)

>>> interval = datetime.timedelta(seconds=0.06)

>>> for i in timeout\_generator(timeout, interval, interval\_multiplier=2):

...     print(i)

0

1

```

### Module contents[¶](#module-python_utils "Permalink to this headline")

Travis status:

[![https://travis-ci.org/WoLpH/python-utils.png?branch=master](https://travis-ci.org/WoLpH/python-utils.png?branch=master)](https://travis-ci.org/WoLpH/python-utils)

Coverage:

[![https://coveralls.io/repos/WoLpH/python-utils/badge.png?branch=master](https://coveralls.io/repos/WoLpH/python-utils/badge.png?branch=master)](https://coveralls.io/r/WoLpH/python-utils?branch=master)

Indices and tables[¶](#indices-and-tables "Permalink to this headline")

=======================================================================

* [Index](genindex.html)

* [Module Index](py-modindex.html)

* [Search Page](search.html)

### [Table of Contents](index.html#document-index)

* [Useful Python Utils](index.html#document-usage)

	+ [Links](index.html#links)

	+ [Requirements for installing:](index.html#requirements-for-installing)

	+ [Installation:](index.html#installation)

	+ [Quickstart](index.html#quickstart)

	+ [Examples](index.html#examples)

* [python\_utils package](index.html#document-python_utils)

	+ [Submodules](index.html#submodules)

	+ [python\_utils.decorators module](index.html#module-python_utils.decorators)

	+ [python\_utils.converters module](index.html#module-python_utils.converters)

	+ [python\_utils.formatters module](index.html#module-python_utils.formatters)

	+ [python\_utils.import\_ module](index.html#module-python_utils.import_)

	+ [python\_utils.logger module](index.html#module-python_utils.logger)

	+ [python\_utils.terminal module](index.html#module-python_utils.terminal)

	+ [python\_utils.time module](index.html#module-python_utils.time)

	+ [Module contents](index.html#module-python_utils)

### Related Topics

* [Documentation overview](index.html#document-index)

### Quick search

 © Copyright 2022, [Rick van Hattem](http://wol.ph/).

 Created using [Sphinx](http://sphinx.pocoo.org/).

 

