简体   繁体   中英

python datetime difference in days and hours

I want to compare two datetime instances and show the how many days and hours that differs. Now I do that with .days and it does seem to work but pylint complains about it.

Is there a better way to do it since pylint complains about it?

#!/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()

This is the output I get from 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)


...

You don't need to import the timedelta name; you can safely remove it from your import list:

from datetime import datetime

Just because subtracting datetime objects produces objects of that type does not mean you need to import the type itself.

As for the other lines, pylint simply is making a wrong inference. You can safely ignore those lines. You can disable that warning by using a comment for the print() line:

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

You can apply the comment to the whole function too:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM