Calculating the time difference between two datetime values in Python

16,659

The 24 hour format is %H, a capital H, not a lowercase. The same for the minutes and seconds. You'll need a space as well, and you have a year format without the century, so use lower-case y:

date_format = "%m/%d/%y %H:%M:%S"

See the strftime() and strptime() behaviour documentation. %h doesn't exist as a format character.

And instead of using time.strftime('%c') to represent now, then parse that again, use:

b = datetime.now()

datetime.timedelta objects do not have an hours attribute; calculate the hours from the total seconds in the delta:

delta = b - a
print(delta.total_seconds() // 60)

or compare the delta object against another timedelta():

if delta > timedelta(hours=23):

Demo:

>>> from datetime import datetime
>>> date_format = "%m/%d/%y %H:%M:%S"
>>> datetime.strptime('12/28/13 16:49:19', date_format)
datetime.datetime(2013, 12, 28, 16, 49, 19)
Share:
16,659

Related videos on Youtube

imfromsweden
Author by

imfromsweden

Updated on September 15, 2022

Comments

  • imfromsweden
    imfromsweden over 1 year

    I want to compare two date and times with each other and then use that information for other stuff. Like if delta > 23 hours do this, elif delta > 11 hours, do that etc. I thought this would be a reasonable way to write it, but python won't accept it! It says:

    ValueError: 'h' is a bad directive in format '%m/%d/%Y%h:%m:%s'
    

    Isn't h the standard way to write hours in Python? :o

    My dates are written in this format: "12/28/13 16:49:19", "m/d/y h:m:s" if that's any help!

    from datetime import datetime
    date_format = "%m/%d/%Y%h:%m:%s"
    then=(dictionary["date"])
    now= time.strftime("%c")
    a = datetime.strptime(str(then), date_format)
    b = datetime.strptime(str(now), date_format)
    delta = b - a
    print(delta.hour)
    
  • jfs
    jfs over 10 years
    Why would you truncate hours with //? You could use / (float division) or compare using delta > timedelta(hours=23).
  • Martijn Pieters
    Martijn Pieters over 10 years
    @J.F.Sebastian: because I'd view hours as a whole number. I like the timedelta(hours=23) idea though.
  • jfs
    jfs over 10 years
    If hours is a whole number then delta > 23 from the question that you are trying to answer doesn't make sense (datetime accepts hours in 0..23 (including)).