1

I have a string variable some_time = "12:30", and I want to add 2 hours to it so the result is "14:30".

I believe by first turning the string into a timeformat,

temp_time = datetime.datetime.strptime(thetime, '%H:%M').time()

so that

>>>print (temp_time)
12:30:00

And then use Pytz can solve it. But I can't seem to find a Pytz command that deals with hh:mm alone, without yy:dd:mm

Any solutions?

  • 1
    Have you played around with [timedelta](https://docs.python.org/3/library/datetime.html#timedelta-objects) to see if it helps? – idjaw Jul 04 '18 at 01:21
  • I think [this](https://stackoverflow.com/questions/18817750/python-datetime-add) might answer your question – idjaw Jul 04 '18 at 01:21
  • Why are you talking about `pytz` here? Are you trying to add arbitrary hours to a timestamp, or are you trying to do something different, like convert from a UTC timestamp to an aware local timestamp in some particular timezone? – abarnert Jul 04 '18 at 01:23
  • Anyway, the reason any timezone library is going to need a date is simple. For converting from UTC to Pacific, how many hours do you add? Depends whether it’s during Daylight Saving Time. Many timezones have also changed permanently at various historic dates (which are all in the tzdb). Even if you just want to subtract an hour, what if it’s 30 minutes away from a DST changeover time in your timezone, so, e.g., an hour before 02:30 is 00:30? If you don’t want `datetime` to deal with any of those complexities, you don’t really want a real timezone object, you just want an offset. – abarnert Jul 04 '18 at 01:27
  • 1
    … and you also probably want a `datetime.time` object, not a `datetime.datetime` (you can call the `temp_time.time()` method to get one). – abarnert Jul 04 '18 at 01:28
  • abarnert: Apologiez, Pytz mentioned the use of timedelta as a solution, so I thought perhaps it was part of Pytz. lenik: Thanks for the reference, it did have the answer! I was just unsure initially on how it would work without the y:m:d – Preben Brudvik Olsen Jul 04 '18 at 01:51

1 Answers1

5

If you use a timedelta, you can add two hours like:

Code:

def add_two_hours(time_string):
    the_time = dt.datetime.strptime(time_string, '%H:%M')
    new_time = the_time + dt.timedelta(hours=2)
    return new_time.strftime('%H:%M')

Test Code:

import datetime as dt

print(add_two_hours('12:30'))
print(add_two_hours('23:30'))

Results:

14:30
01:30
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135