0

I'm trying to shift a time forward or backward depending on some integer value. So far, I've been just adding (or subtracting) that time shift from the hour then using mod 24 when I create the time

time_structure = datetime.time((hour + time_zone_shift)%24, minute, second) 

This works for the most part (except with rolling back the date, i.e if the time given is 7:30 and then the time_zone_shift is -8). I was wondering if there is a more "pythonic" way to do this?

mattexx
  • 6,456
  • 3
  • 36
  • 47
Evan
  • 508
  • 1
  • 5
  • 18

1 Answers1

0

So to answer your question, you should use datetime.timedelta to offset a time:

time_structure = (datetime.datetime(0, 0, 0, hour, minute, second) + datetime.timedelta(hours=time_zone_shift)).time()

But as expressed in the comments, you should really use pytz for time zone math since it can be rather complicated.

mattexx
  • 6,456
  • 3
  • 36
  • 47