0

I need to work with datetime but I can't find how to subtract or add minutes or seconds from a datetime.time object

I've tried to use datetime.timedelta but it doesn't work.

Here is what I've tried

t1=datetime.time(15,45,20)
t2=t1-datetime.timedelta(seconds=40)

I would like to obtain t2=datetime.time(15,44,40)

2
  • 2
    Please clarify "doesn't work" with a minimal reproducible example. There's a reason it requires a full datetime - what should happen if subtracting 40 seconds takes you into the previous day? Commented Dec 21, 2016 at 20:18
  • 1
    You can't subtract a timedelta from a time, only from a datetime. Also, your question title is misleading, as you apparently don't want to manipulate dates at all, only times. Commented Dec 21, 2016 at 20:22

1 Answer 1

1

Timedelta works with datetime objects. You could make your time into a datetime (or just start with one, who cares what the year, etc is), and then extract a time object back out.

>>>t1=datetime.datetime(2016, 3, 1, 15,45,20)
>>>t2=t1-datetime.timedelta(seconds=40)
>>>print t2.time()
15:44:40
>>>type(t2.time())
<type 'datetime.time'>

As one of the comments pointed out, this can give you odd results if you don't think about it. Take 40 seconds off, and end up with a time that's later (but a day earlier on the date data you are ignoring). But you can work around that with minimal logic to catch things that are going to go over 24:00:00 or under 0:0:0.

Sign up to request clarification or add additional context in comments.

Comments

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.