Jkev
Jkev

Reputation: 197

How to manipulate time objects in Python?

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)

Upvotes: 0

Views: 139

Answers (1)

TinBane
TinBane

Reputation: 936

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.

Upvotes: 1

Related Questions