datetime_truncate_10.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. def truncate(datetime, truncate_to='day'):
  2. '''
  3. Truncates a datetime to have the values with higher precision than
  4. the one set as `truncate_to` as zero (or one for day and month).
  5. Possible values for `truncate_to`:
  6. * second
  7. * minute
  8. * hour
  9. * day
  10. * week (iso week i.e. to monday)
  11. * month
  12. * quarter
  13. * half_year
  14. * year
  15. Examples::
  16. >>> truncate(datetime(2012, 12, 12, 12), 'day')
  17. datetime(2012, 12, 12)
  18. >>> truncate(datetime(2012, 12, 14, 12, 15), 'quarter')
  19. datetime(2012, 10, 1)
  20. >>> truncate(datetime(2012, 3, 1), 'week')
  21. datetime(2012, 2, 27)
  22. :params datetime: an initialized datetime object
  23. :params truncate_to: The highest precision to keep its original data.
  24. :return: datetime with `truncated_to` as the highest level of precision
  25. :rtype: :py:mod:`datetime` datetime object
  26. '''
  27. if truncate_to in PERIODS:
  28. return datetime.replace(**PERIODS[truncate_to])
  29. elif truncate_to in ODD_PERIODS:
  30. if truncate_to == 'week':
  31. return truncate_week(datetime)
  32. elif truncate_to == 'quarter':
  33. return truncate_quarter(datetime)
  34. elif truncate_to == 'half_year':
  35. return truncate_half_year(datetime)
  36. else:
  37. raise ValueError('truncate_to not valid. Valid periods: {}'.format(
  38. ', '.join(PERIODS.keys() + ODD_PERIODS)
  39. ))