Skip to content

Instantly share code, notes, and snippets.

@Shide
Created December 11, 2018 12:26
Show Gist options
  • Save Shide/a2cf30bedb50654d7f37f19320109586 to your computer and use it in GitHub Desktop.
Save Shide/a2cf30bedb50654d7f37f19320109586 to your computer and use it in GitHub Desktop.
Datetime Tools
def timedelta_datetime_list(date_list, reverse=False, expanded_info=False):
"""
Gives the difference between the date element and the next one.
:param date_list: list of datetime/date objects
:type date_list: list
:param reverse: How the list should be sorted list.sort(reverse=<True,False>)
:type reverse: bool
:param expanded_info: Adds the first and second date on the yield as return parameters.
:type expanded_info: bool
:return: Yields the difference between the current date element and the next one.
:return type: datetime.timedelta + Optional: *(datetime.datetime, datetime.datetime)
"""
date_list.sort(reverse=reverse)
date_init, i = date_list[0], 1
while i < len(date_list):
if expanded_info:
yield date_list[i] - date_init, date_list[i], date_init
else:
yield date_list[i] - date_init
date_init, i = date_list[i], i + 1
def xrange_date(date_start_obj, date_end_obj, timedelta_obj):
"""
`xrange` adaptation for date and datetime objects.
:param date_start_obj: date to start
:type date_start_obj: datetime.date, datetime.datetime
:param date_end_obj: date to end
:type date_end_obj: datetime.date, datetime.datetime
:param timedelta_obj: increment or decrement for iteration
:type timedelta_obj: datetime.timedelta, dateutil.relativedelta.relativedelta
:return: Yields elements while dt_start (</>) dt_end.
:return type: datetime.date, datetime.datetime
"""
if (getattr(timedelta_obj, 'total_seconds', False) and timedelta_obj.total_seconds() or timedelta_obj) >= 0:
cp_modifier = type(date_start_obj).__le__
else:
cp_modifier = type(date_start_obj).__ge__
while cp_modifier(date_start_obj, date_end_obj):
yield date_start_obj
date_start_obj = date_start_obj + timedelta_obj
def timedelta_to_hhmmss(tdelta, to_string=False):
"""
Converts timedelta on hours, minutes and seconds.
:param tdelta: datetime.timedelta object
:param to_string: Parses response to text formatted with leading zeroes.
:return: hours, minutes, seconds
:rtype: int, int, int
"""
hh, mm = divmod(abs(tdelta.total_seconds() / 60.0), 60.0)
_, ss = divmod(abs(timedelta(minutes=mm).total_seconds()), 60.0)
if to_string:
return '%02i' % int(hh), '%02i' % int(mm), '%02i' % int(ss)
return int(hh), int(mm), int(ss)
@Shide
Copy link
Author

Shide commented Dec 11, 2018

Some useful Date tools.

Feel free to copy/modify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment