-2

I did so:

str_7 = str(waiting_time - timedelta(microseconds=waiting_time.microseconds)).split(":")
col_7 = time(int(str_7[0]), int(str_7[1]), int(str_7[2]))

Is this code correct?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cícero Alves
  • 153
  • 1
  • 2
  • 6
  • waiting_time is a datetime. – Cícero Alves Dec 29 '14 at 18:46
  • http://stackoverflow.com/questions/2119472/convert-a-timedelta-to-days-hours-and-minutes – ndpu Dec 29 '14 at 18:50
  • Not sure what you're trying to do here. `timedelta` is logically a difference between two points in time and time is usually a single point in time. Sounds like you're trying to convert apples to oranges. Can we get some more context about your problem? – elifiner Dec 29 '14 at 18:54
  • Also, your variable names seem to suggest you're doing multiple similar things one after another. It might be better to use a loop. – elifiner Dec 29 '14 at 18:55

1 Answers1

5

If waiting_time is a datetime, then waiting_time - timedelta() is also a datetime. You can just use .time() on that object to get the datetime.time() object from that:

new_dt = waiting_time - timedelta(microseconds=waiting_time.microseconds)
col_7 = new_dt.time()

However, if all you are doing is remove the waiting_time.microseconds component, then do so with the datetime.datetime.replace() method:

col_7 = waiting_time.replace(microsecond=0).time()

or, if you need to produce a string for just the time, then use datetime.strftime() to produce a string that simply ignores the microseconds component:

col_7 = waiting_time.strftime('%H:%M:%S')  # hours:minutes:seconds
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    `waiting_time - timedelta()` is a timedelta, not a datetime. if datetime - timedelta, the result is timedelta. – Cícero Alves Dec 30 '14 at 12:49
  • @CíceroAlves: no, `datetime - datetime` gives you a timedelta. `datetime - timedelta()` gives you a new `datetime`. Are you saying `waiting_time` is a timedelta instead? `timedelta - timedelta` gives you a `timedelta` too. – Martijn Pieters Dec 30 '14 at 12:51
  • new_dt = waiting_time - timedelta(microseconds=waiting_time.microseconds) is a timedelta, you can't add to it .time() – newbie Nov 19 '19 at 07:53
  • 1
    @A.khou: that’s the same conversation I had with Cicero. **It depends on the type of `waiting_time`** what is returned when you subtract a `timedelta` instance. – Martijn Pieters Nov 19 '19 at 09:19