1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- def truncate(datetime, truncate_to='day'):
- '''
- Truncates a datetime to have the values with higher precision than
- the one set as `truncate_to` as zero (or one for day and month).
- Possible values for `truncate_to`:
- * second
- * minute
- * hour
- * day
- * week (iso week i.e. to monday)
- * month
- * quarter
- * half_year
- * year
- Examples::
- >>> truncate(datetime(2012, 12, 12, 12), 'day')
- datetime(2012, 12, 12)
- >>> truncate(datetime(2012, 12, 14, 12, 15), 'quarter')
- datetime(2012, 10, 1)
- >>> truncate(datetime(2012, 3, 1), 'week')
- datetime(2012, 2, 27)
- :params datetime: an initialized datetime object
- :params truncate_to: The highest precision to keep its original data.
- :return: datetime with `truncated_to` as the highest level of precision
- :rtype: :py:mod:`datetime` datetime object
- '''
- if truncate_to in PERIODS:
- return datetime.replace(**PERIODS[truncate_to])
- elif truncate_to in ODD_PERIODS:
- if truncate_to == 'week':
- return truncate_week(datetime)
- elif truncate_to == 'quarter':
- return truncate_quarter(datetime)
- elif truncate_to == 'half_year':
- return truncate_half_year(datetime)
- else:
- raise ValueError('truncate_to not valid. Valid periods: {}'.format(
- ', '.join(PERIODS.keys() + ODD_PERIODS)
- ))
|