2

This line of code is receiving an AttributeError: now = timezone.now()

I can't figure out why. I am correctly importing the package as follows: from django.utils import timezone

But it is still throwing:

Attribute Error: type object 'datetime.timezone' has no attribute 'now'

Model

class Donaci(models.Model):
    creation_date = models.DateTimeField(auto_now_add=True, blank=True)
    message = models.CharField(max_length=300, null=True, blank=True)

    def whenpublished(self):
        now = timezone.now()
        
        diff = now - self.creation_date

        if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60:
            seconds= diff.seconds
            
            if seconds == 1:
                return str(seconds) +  "second ago"
            
            else:
                return str(seconds) + " seconds ago"

Imports

from django.contrib.auth.models import AbstractUser
from django.contrib.auth import settings
from django.utils import timezone
from django.db import models
from datetime import *
Nicolas
  • 39
  • 1
  • 6

2 Answers2

0

The answer is:

from django.utils import timezone
from datetime import *

first imports timezone from django.utils but then this gets overridden by your * import from Python's datetime module which also has timezone (and many other things).

When you do timezone.now(), it's using Python's datetime timezone object instead of django.utils timezone object, which is why you see the error:

AttributeError: type object 'datetime.timezone' has no attribute 'now'

If you had imported the other way around:

from datetime import *
from django.utils import timezone

timezone.now() would work because the timezone object would be overridden by django.utils timezone object.

Advice: don't do star imports unless you know it won't conflict.

Jarad
  • 17,409
  • 19
  • 95
  • 154
-2

Use this:

import datetime

instead of this:

from datetime import *
Reza Rahemtola
  • 1,182
  • 7
  • 16
  • 30
Anuprasad
  • 1
  • 3