Search code examples
pythondatetimepython-2.7strftimestrptime

Adding and substracting hours to a 24 hour time in python?


I need to subtract 5 hours from the string "03:40"

I've tried the following:

import datetime

timevar = "03:40"
newtime = datetime.datetime.date.strftime("%H:%M", timevar)
newtime = newtime - datetime.timedelta(hours=5)
print newtime

I've read the datetime documentation but I still can't see what I'm doing wrong.

Any help much appreciated.
- Hyflex


Solution

  • You've got a few problems... First, you're looking for strptime and not strftime. Second, strptime is a method on datetime.datetime, not datetime.datetime.date. Third, you've got the order of the arguments mixed up. This should be what you want:

    newtime = datetime.datetime.strptime(timevar, "%H:%M")
    newtime -= datetime.timedelta(hours=5)
    

    *Note, this gives you a date portion that is somewhere around January 1st, 1900. It seems like you only want the time portion, so that probably doesn't matter -- But I thought it would be worth mentioning.