1

I need some help with my code. I have got an error when I am trying to add 30 mins with getTime3.

import datetime
import time

getTime3 = '12:30AM'
dt3 = time.strptime(getTime3, '%I:%M%p')
test_time = dt3 + datetime.timedelta(minutes = 30)

print test_time

The error are jumping on this line:

test_time = dt3 + datetime.timedelta(minutes = 30)

Here is what dt3 show the struct_time object:

time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)

Here is what test_time show the object without the dt3:

0:30:00

Can you please help me with how I could correct the error to allow me to add the minutes?

Daniel Ezekiel
  • 133
  • 2
  • 4
  • 11
  • 1
    you're using the `time` version of `strptime`, which [returns a `struct_time`](https://docs.python.org/2/library/time.html#time.strptime); you probably want to be using the `datetime` version of `strptime`, [which returns a `datetime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) – Hamms Sep 12 '17 at 23:42
  • @Hamms I am sorry but i cant use datetime version of strptime because the application I am running will only allow me to use `time` version of strtime which it works fine. – Daniel Ezekiel Sep 12 '17 at 23:45
  • @Hamms please see the update in my question – Daniel Ezekiel Sep 12 '17 at 23:45
  • That seems pretty strange to me, but in that case I'd just [convert the struct_time to a datetime](https://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object) – Hamms Sep 12 '17 at 23:48

2 Answers2

1

The easiest way to manipulate the time.struct_time type is by converting it to seconds since epoch, and vice versa.

In your particular case, you want to add 30 minutes, that will be 30 * 60 seconds:

test_time = time.localtime(time.mktime(dt3) + 30*60))
rodrigo
  • 94,151
  • 12
  • 143
  • 190
0

I would use just datetime module for better handling dates and times:

import datetime

format = '%I:%M%p'
getTime3 = '12:30AM'
dt3 = datetime.datetime.strptime(getTime3, format)
test_time = dt3 + datetime.timedelta(minutes = 30)

print(test_time.time().strftime(format))
y.luis.rojo
  • 1,794
  • 4
  • 22
  • 41