【问题标题】:Python timedelta receiving unexpected resultsPython timedelta 收到意外结果
【发布时间】:2011-10-31 09:25:18
【问题描述】:

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

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 需要一种简单的方法来对其进行排序。我面临的问题是整数和字符串不匹配,正如您在此屏幕截图中看到的那样:

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

编辑

对于屏幕截图顶部的记录,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

【问题讨论】:

  • “搞砸了”?请具体说明您发现“搞砸”的具体内容。如果有任何方法可以生成值的简单文本列表(不是屏幕截图),那将不胜感激。

标签: python datetime methods time timedelta


【解决方案1】:

如果要获取timenow 之间的秒数,请使用

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

【讨论】:

  • 谢谢,已经解决了!
【解决方案2】:

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

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

【讨论】:

  • return remaining 是它的转换,它有效地运行 str(datetime.timedelta)