假设我有时间04:05,时区是-0100(GMT)
我想计算新时间03:05
python中有任何函数可以进行计算吗?
由于
答案 0 :(得分:1)
尝试这样的事情:
>>> import datetime
>>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
>>> my_time
datetime.datetime(1900, 1, 1, 4, 5)
>>> offset_str = '-0100'
>>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
>>> offset
datetime.timedelta(-1, 82800)
>>> my_time + offset
datetime.datetime(1900, 1, 1, 3, 5)
>>> (my_time + offset).time()
datetime.time(3, 5)
简而言之:
>>> import datetime
>>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
>>> offset_str = '-0100'
>>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
>>> (my_time + offset).time()
datetime.time(3, 5)
答案 1 :(得分:0)
您可以使用“pytz”来完成此任务。尝试:
from string import atoi
from datetime import datetime
import pytz # Available http://sourceforge.net/project/showfiles.php?group_id=79122
thedate = "20080518"
thetime = "2210"
europe_tz = pytz.timezone('Europe/Paris') # Note that your local install timezone should be settings.py
brazil_tz = pytz.timezone('America/Sao_Paulo')
server_tz = pytz.timezone('America/Los_Angeles')
stat_time = datetime(atoi(thedate[0:4]), atoi(thedate[4:6]), atoi(thedate[6:8]), atoi(thetime[0:2]), atoi(thetime[2:4]), 0, tzinfo=europe_tz)
stat_time.astimezone(brazil_tz) # returns time for brazil
stat_time.astimezone(server_tz) # returns server time
来源:http://menendez.com/blog/python-timezone-conversion-example-using-pytz/