Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the time difference between two datetime values in Python

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)
like image 637
imfromsweden Avatar asked Mar 21 '23 04:03

imfromsweden


1 Answers

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)
like image 158
Martijn Pieters Avatar answered Apr 06 '23 02:04

Martijn Pieters