3

在我正在为现有数据库编写的 Web 应用程序中,我需要计算现在与存储在数据库中的时间戳之间的差异(在文本字段中,这很愚蠢,我知道)。这是我的 sqlalchemyBan类和相关方法。

class Ban(base):
    __tablename__= 'bans'

    id= Column('banID', Integer, primary_key=True)
    unban_timestamp= Column('UNBAN', Text)
    banned_steamid= Column('ID', Text, ForeignKey('rp_users.steamid'))
    banned_name= Column('NAME', Text)
    banner_steamid= Column('BANNER_STEAMID', Text, ForeignKey('rp_users.steamid'))
    banner_name= Column('BANNER', Text)
    reason= Column('REASON', Text)

    def unbanned_in(self, mode):
        if self.unban_timestamp == '0':
            return 'Never'
        else:
            now= datetime.datetime.utcnow()
            time= datetime.datetime.fromtimestamp(int(self.unban_timestamp))
            if now > time:
                return 'Expired'
            else:
                remaining= time - now
                if mode=='readable':
                    return remaining
                elif mode=='int':
                    return str(remaining.seconds).zfill(10)

我需要整数和漂亮的字符串表示,因为我将在 html 表中呈现它,而 javascript 需要一种简单的方法来对其进行排序。我面临的问题是整数和字符串不匹配,如您在此屏幕截图中所见:

示例 html 表

如果有人能理解为什么输出如此糟糕,那将不胜感激!如果您需要更多信息来回答我的问题,我很乐意添加它。

编辑

对于屏幕截图顶部的记录,unbanned_in 时间戳是1320247970如果我通过我的函数运行它,这就是我得到的结果

>>> ban = session.query(db.Ban).filter_by(id=3783).one()
>>> print ban.unbanned_in('int'), ban.unbanned_in('readable')
0000049044 2 days, 13:37:24.179045
4

2 回答 2

1

输出搞砸了,因为您将秒数转换为天、小时、分钟和秒的计算是错误的。由于您没有发布那段代码,我只能说,但请注意,一天有 86400 秒,并且您输出的所有秒数都小于此。

您输出的小时、分钟和秒值看起来不错,只是您的天数计算是错误的。

于 2011-10-31T09:50:44.463 回答
1

time如果您想获取and之间的秒数,请now使用

remaining.days * 24 * 3600 + remaining.seconds 而不仅仅是remaining.seconds

于 2011-10-31T09:53:45.000 回答