[Django]-Django DateTimeRangeField: default=[timezone.now()]-[timezone.now()]+[10YEARS]

4👍

There’s no need for string manipulation, as the documented Python type for this field is DateTimeTZRange.

I can’t say I’ve ever used this field before, but something like this should work:

from psycopg2.extras import DateTimeTZRange
from django.utils import timezone
from datetime import timedelta

def next_ten_years():
    now = timezone.now()

    # use a more accurate version of "10 years" if you need it
    return DateTimeTZRange(now, now + timedelta(days=3652))

class MyModel(models.Model):
    ...
    active_in = models.DateTimeRangeField(default=next_ten_years)

Leave a comment