Using Python 2.7, how can I convert a given time from one offset to another? My solution below treats offsets as a time and ignores the sign (+/-) leading to incorrect conversions.
import time
from datetime import datetime
import re
# inputs (cannot change)
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '-0100'
# conversion
from_time = time.strptime(from_time_str, '%H:%M')
from_offset_time = time.strptime(from_offset, '-%H%M')
to_offset_time = time.strptime(to_offset, '-%H%M')
offset_diff = abs(time.mktime(to_offset_time) - time.mktime(from_offset_time))
to_timestamp = offset_diff + time.mktime(from_time)
to_datetime = datetime.fromtimestamp(to_timestamp)
print to_datetime.strftime('%H:%M')
Output:
19:45
+/-:
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '+0700'
to_offset_time = time.strptime(to_offset, '+%H%M')
Output:
13:45