1

我正在 Django 中编写一个 URL 缩短器应用程序。我想检查一个 URL 是否过期(URL 仅在 3 小时内有效)。下面是我的models.py,但它不工作我收到错误can't subtract datetime object

import uuid
import base64
import datetime
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------ 

def _generateShortUrl():
    """
        This function will generate base64 encoded id
    """
    return base64.urlsafe_b64encode(uuid.uuid1().bytes)[:6]


class link(models.Model):
    """
        This is a link class 
    """
    link = models.URLField()                                    # To store user entered URL
    hits = models.IntegerField(default=0)                       # How many hits for particular URL
    last_used = models.DateTimeField(auto_now=True)             # When URL is last used 
    short_url = models.CharField(max_length=6,unique=True)      # base64 URL encoded id  

    def linkValidate(self):
        timediff = datetime.datetime.now() - self.last_used                       
        return timediff.min

    def save(self, *args, **kwargs):
        """
            Custom Save method for link model 
        """
        self.short_url = _generateShortUrl()        
        super(link, self).save(*args, **kwargs)   


class user_info(models.Model):
    """
        This is a user_info class 
    """
    user_agent = models.TextField()                 # Stores user_agent name used by user
    user_ip = models.ManyToManyField(link)          # Stores user's IP

    def userIP(self):
        """Method to return tags related to store"""
        return ','.join([t.link for t in self.link.all()])

#------------------------------------------------------------------------------ 

class linkAdmin(admin.ModelAdmin):
    """
        link admin class
    """
    list_display = ('link','hits','short_url','last_used',
                    'linkValidate')
    ordering = ('hits',)

class userInfoAdmin(admin.ModelAdmin):
    """
        user_info admin class
    """
    list_display = ('user_agent','userIP')

#------------------------------------------------------------------------------ 
admin.site.register(link,linkAdmin)
admin.site.register(user_info,userInfoAdmin)

有人可以帮帮我吗。

4

1 回答 1

4

由于您启用了时区支持,self.last_used因此它是一个时区感知的日期时间对象,datetime.datetime.now()不是。

试试这个:

timediff = datetime.datetime.utcnow() - self.last_used.replace(tzinfo=None)

另一种选择是让您的now()时区感知使用make_aware()

from django.utils import timezone
now = timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone())
timediff = now() - self.last_used

另见:

于 2013-09-06T18:10:32.853 回答