简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM