Username
Username

Reputation: 3663

How do I make a model with a datetime field that does NOT save the time zone?

I have a model that looks like this:

class IPLog(models.Model):
    last_click = models.DateTimeField()

When I save an IPLog instance, the time zone gets saved with it. This is a problem for me since I want to compare last_click to a datetime.now() instance, but it throws me an error since the model instance's last_click has a time zone: TypeError: can't subtract offset-naive and offset-aware datetimes.

The difference tends to look like this:

2018-03-16 00:24:35.619424 # datetime.now()
2018-03-15 23:55:07.006190+00:00 # last_click

How do I stop my model from saving new instances with a time zone?

Upvotes: 0

Views: 29

Answers (1)

bonidjukic
bonidjukic

Reputation: 1479

Instead of comparing to datetime.now() you should compare to timezone.now():

from django.utils import timezone

now = timezone.now()

You can read more about timezone aware datetime objects here.

Upvotes: 1

Related Questions