Skip to content

Instantly share code, notes, and snippets.

@vguhesan
Last active October 25, 2023 03:39
Show Gist options
  • Save vguhesan/80be34ccaef4def1d8a379a8b6e78060 to your computer and use it in GitHub Desktop.
Save vguhesan/80be34ccaef4def1d8a379a8b6e78060 to your computer and use it in GitHub Desktop.
Python Humanize timedelta without Arrow or Humanize library

Python Humanize timedelta without Arrow or Humanize library

Given 2 dates that are formatted from a string to arrow type.

>>> from datetime import datetime 
>>> start = datetime.now()
>>> end = datetime.now()
>>> diff = end - start

The difference is a datetime.timedelta data type.

>>> print type(diff)
<class 'datetime.timedelta'>

And results in:

>>> print diff
692 days, 18:37:32

To get it formatted such that you would have D days, H hours, M minutes, S seconds you would get the days separately, and then using divmod function get the other information.

>>> days = diff.days # Get Day 
>>> hours,remainder = divmod(diff.seconds,3600) # Get Hour 
>>> minutes,seconds = divmod(remainder,60) # Get Minute & Second 

The result would be:

>>> print(f'Elapsed Time: {days} Days, {hours} Hours, {minutes} Minutes, {seconds} Seconds.')
692  Days,  18  Hours,  37  Minutes,  32  Second
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment