简体   繁体   中英

How to find difference between both dates and times?

from datetime import *
from time import *

release = "15-07-2015 23:59:59"
now = datetime.now()

currentTime = (now.strftime("%d-%m-%Y %H:%M:%S"))
release = datetime.strptime(release, "%d-%m-%Y %H:%M:%S")


currentTime = datetime.strptime(currentTime, "%d-%m-%Y %H:%M:%S")

diff = release - currentTime

(diff.strftime("%m Months %dDays %Y Years %H Hours %M Minutes %S Seconds")) 

This is what I've been working with... I've tried for ages to get this to work properly but I can only get an error saying:

AttributeError: 'datetime.timedelta' object has no attribute 'strftime'

I'd appreciate help please.

The problem is exactly what it says: timedelta objects don't have a strftime method. If you want to format a timedelta , you have to do it manually. (Or use a third-party library that provides more features.)

Also, note that the specific output you're looking for doesn't even really make sense. Time deltas don't do months and years, just days and seconds—because months and years wouldn't make sense. 35 days is 35 days no matter when you start counting, but 1 month and 5 days may be anywhere from 33 days to 36, so it's not a consistent time delta.

You can use dateutil.relativedelta :

from dateutil import relativedelta
diff = relativedelta.relativedelta(release, currentTime)

print("{} Months {} Days {} Years {} Hours {} Minutes {} Seconds".format(
            diff.months,diff.days,diff.years,
            diff.hours, diff.minutes,diff.seconds))

3 Months 2 Days 0 Years 10 Hours 37 Minutes 25 Seconds

If you don't have it installed you can install it with pip:

  pip install python-dateutil

In case, you don't want to use dateutil , you need to write a custom strftime like strftimedelta and as @abarnet suggested with only (days, hours, seconds) ifro

def strftimedelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    return fmt.format(**d)

strftimedelta(diff, "{days} days {hours} hours {minutes} minutes {seconds} seconds")

'93 days 6 hours 19 minutes 3 seconds'

http://www.tutorialspoint.com/python/time_strftime.htm

time.strftime(format[, t])

time.strftime("%b %d %Y %H:%M:%S", diff) (or try time.gmtime(diff) like shown on the link)

You are using diff.strftime, and diff doesnt know strftime, the imported time does, so try time.strftime

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