Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 880
Ryflex Avatar asked Apr 07 '26 07:04

Ryflex


1 Answers

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.

like image 52
mgilson Avatar answered Apr 08 '26 19:04

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!