4

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)

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Why would you truncate hours with //? You could use / (float division) or compare using delta > timedelta(hours=23).
@J.F.Sebastian: because I'd view hours as a whole number. I like the timedelta(hours=23) idea though.
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)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.