Created
January 27, 2016 03:59
-
-
Save bencharb/cbd196ba0223c6072079 to your computer and use it in GitHub Desktop.
distribute time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def distribute_time(dt, count=-1, step=1, unit='hours', round_time=True): | |
| """ | |
| Examples: | |
| In [01]: | |
| list(distribute_time(dt, -3)) | |
| Out[01]: | |
| [datetime.datetime(2016, 1, 26, 22, 0), | |
| datetime.datetime(2016, 1, 26, 21, 0), | |
| datetime.datetime(2016, 1, 26, 20, 0)] | |
| In [02]: | |
| list(distribute_time(dt, 3, unit='days')) | |
| Out[02]: | |
| [datetime.datetime(2016, 1, 26, 0, 0), | |
| datetime.datetime(2016, 1, 27, 0, 0), | |
| datetime.datetime(2016, 1, 28, 0, 0)] | |
| """ | |
| td_units = 'days', 'hours', 'minutes', 'seconds', | |
| if round_time: | |
| dt_units = dt.day, dt.hour, dt.minute, dt.second | |
| dt_args = [dt.year, dt.month] | |
| for td_unit, dt_arg in zip(td_units, dt_units): | |
| dt_args.append(dt_arg) | |
| if td_unit == unit: | |
| break | |
| dt = datetime.datetime(*dt_args) | |
| op = operator.sub if count < 0 else operator.add | |
| yield dt | |
| for x in xrange(abs(count)-1): | |
| yield op(dt, datetime.timedelta(**{unit:x+step})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment