python datetime以天和小时的差异

时间:2015-11-29 14:15:15

标签: python datetime

我想比较两个日期时间实例,并显示不同的天数和小时数。现在我用.days做到这一点似乎确实有效,但是pylint抱怨它。

因为pylint抱怨它,有更好的方法吗?

#!/usr/bin/python
"""A test of time differences"""

from datetime import datetime, timedelta

REF_DATE = datetime.strptime("2015-01-01", "%Y-%m-%d")

def main():
    """Main function"""
    today = datetime.now()
    tdiff = today - REF_DATE
    print("Difference is %d days %d hours" % (tdiff.days, tdiff.seconds/3600))

main()

这是我从pylint得到的输出:

No config file found, using default configuration
************* Module test_timedelta
E: 12,52: Instance of 'datetime' has no 'days' member (but some types could not be inferred) (maybe-no-member)
E: 12,64: Instance of 'datetime' has no 'seconds' member (but some types could not be inferred) (maybe-no-member)
W:  4, 0: Unused import timedelta (unused-import)


...

1 个答案:

答案 0 :(得分:2)

您不需要导入timedelta名称;您可以安全地从导入列表中删除它:

from datetime import datetime

仅仅因为减去datetime个对象会产生该类型的对象并不意味着您需要自己导入该类型。

至于其他行,pylint只是做出了错误的推断。你可以安全地忽略这些行。您可以使用print()行的注释来禁用该警告:

tdiff = today - REF_DATE
print("Difference is %d days %d hours" % (
    tdiff.days, tdiff.seconds/3600))  #pylint: disable=E1103

您也可以将评论应用于整个功能:

def main():
    """Main function"""
    #pylint: disable=E1103
    today = datetime.now()
    tdiff = today - REF_DATE
    print("Difference is %d days %d hours" % (tdiff.days, tdiff.seconds/3600))