datetime_truncate

This module truncates a datetime object to the level of precision that you specify, making everything higher than that zero (or one for day and month).

It is based on PostgreSQL’s DATE_TRUNC.

datetime_truncate datetime_truncate

datetime_truncate.truncate(datetime, truncate_to='day')[source]

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.
Returns:datetime with truncated_to as the highest level of precision
Return type:datetime datetime object
datetime_truncate.truncate_second(datetime)[source]

Sugar for truncate(datetime, 'second')

datetime_truncate.truncate_minute(datetime)[source]

Sugar for truncate(datetime, 'minute')

datetime_truncate.truncate_hour(datetime)[source]

Sugar for truncate(datetime, 'hour')

datetime_truncate.truncate_day(datetime)[source]

Sugar for truncate(datetime, 'day')

datetime_truncate.truncate_week(datetime)[source]

Truncates a date to the first day of an ISO 8601 week, i.e. monday.

Params datetime:
 an initialized datetime object
Returns:datetime with the original day set to monday
Return type:datetime datetime object
datetime_truncate.truncate_month(datetime)[source]

Sugar for truncate(datetime, 'month')

datetime_truncate.truncate_quarter(datetime)[source]

Truncates the datetime to the first day of the quarter for this date.

Params datetime:
 an initialized datetime object
Returns:datetime with the month set to the first month of this quarter
Return type:datetime datetime object
datetime_truncate.truncate_half_year(datetime)[source]

Truncates the datetime to the first day of the half year for this date.

Params datetime:
 an initialized datetime object
Returns:datetime with the month set to the first month of this half year
Return type:datetime datetime object
datetime_truncate.truncate_year(datetime)[source]

Sugar for truncate(datetime, 'year')

Indices and tables