Python 2.7 - 时间偏移转换

时间:2016-03-04 21:15:55

标签: python python-2.7 datetime

使用Python 2.7,如何将给定时间从一个偏移量转换为另一个偏移量?我的解决方案将偏移视为一个时间并忽略符号(+/-)导致错误的转换。

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')

输出:

19:45

+/-:

from_time_str = '13:45'
from_offset = '-0700'
to_offset = '+0700'

to_offset_time = time.strptime(to_offset, '+%H%M')

输出:

13:45

1 个答案:

答案 0 :(得分:1)

如果您愿意使用dateutil库,这似乎有效:

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')

肯定有更多的pythonic方式,但它似乎确实有效!