1

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
rvk
  • 737
  • 3
  • 9
  • 23
  • How about using time [datetime.timedetla()](https://docs.python.org/2/library/datetime.html#timedelta-objects) for this? You can subtract desired number of hours from your datetime object like so: ``datetimeObj - datetime.timedelta(hours=7)`` or ``datetimeObj - datetime.timedelta(hours=3)`` – Igor Mar 04 '16 at 21:34
  • 1
    @Igor I'm having a hard time calculating the difference between two offsets, Ie: difference between +0700 and -0700 is 14, then I can use 14 as the hours in timedelta. Or between -0100 and +0530 is 6 hours and 30 mintues. – rvk Mar 04 '16 at 21:45
  • you are doing something wrong if the purpose of these manipulations is to [convert the time in one timezone to the time in another timezone (you should convert the time into datetime object and provide the corresponding `pytz` tzinfo objects instead).](http://stackoverflow.com/q/10997577/4279) – jfs Mar 04 '16 at 23:12

1 Answers1

1

if you're open to using the dateutil library, this seems to work:

from dateutil.parser import parse
from dateutil.relativedelta import relativedelta

# inputs (cannot change)
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '-0100'


if from_offset[0]=='-':
    non_offset = parse(from_time_str)+relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))
else:
    non_offset = parse(from_time_str)-relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))

if to_offset[0]=='-':
    to_offset_time = non_offset-relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))
else:
    to_offset_time = non_offset+relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))

print to_offset_time.strftime('%H:%M')

I'm sure there is a more pythonic way, but it does seem to work!

Kapocsi
  • 922
  • 6
  • 17