Skip to content

Instantly share code, notes, and snippets.

@squioc
Created September 1, 2013 20:06
Show Gist options
  • Save squioc/6406987 to your computer and use it in GitHub Desktop.
Save squioc/6406987 to your computer and use it in GitHub Desktop.
Format remaining or elapsed time according to thresholds
"""
The MIT License (MIT)
Copyright (c) 2013 Sebastien Quioc
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from datetime import timedelta, datetime
def format_timedelta(delta, formats, reference_datetime=None):
"""
>>> format_list = []
>>> format_list.append((3600, 3600, 'at {1:%H:%M}'))
>>> format_list.append((60, 60, 'in {} minutes'))
>>> format_list.append((10, 1, 'in {} seconds'))
>>> format_list.append((0, 1, 'now'))
>>> format_list.append((-60, 1, '{} seconds ago'))
>>> format_timedelta(timedelta(hours=6), format_list, datetime(2013, 1, 1, 12, 30))
'at 12:30'
>>> format_timedelta(timedelta(minutes=37), format_list)
'in 37 minutes'
>>> format_timedelta(timedelta(seconds=16), format_list)
'in 16 seconds'
>>> format_timedelta(timedelta(seconds=4), format_list)
'now'
>>> format_timedelta(None, format_list)
'now'
>>> format_timedelta(timedelta(seconds=-15), format_list)
'15 seconds ago'
"""
elapsed_or_remaining_time = delta and delta.total_seconds() or 0
reference_datetime = reference_datetime or datetime.now() + timedelta(seconds=elapsed_or_remaining_time)
formats = sorted(formats, cmp=lambda x,y: cmp(x[0], y[0]), reverse=True)
for (threshold, parts, format_string) in formats:
if elapsed_or_remaining_time >= threshold:
return format_string.format(int(abs(elapsed_or_remaining_time) / max(parts, 1)), reference_datetime)
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment