How can I calculate new time zone in python?
Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want t开发者_Python百科o calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks
Try something like this:
>>> 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)
In short:
>>> 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)
You can use "pytz" to accomplish this.Try:
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
Source: http://menendez.com/blog/python-timezone-conversion-example-using-pytz/
精彩评论