Python: Convert local time to another time zone
I want to convert the current time to +0900 in Python.
What's the appropriate way to do this (assuming in the time module)?
I've read this isn't included with Python and you have to开发者_如何学JAVA use something like pytz.
I don't want to change it on a server basis or globally, just in this one instance.
Example for converting data from UTC to IST
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(format)
Output: 2015-05-18 10:02:47 UTC+0000
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print now_asia.strftime(format)
Output: 2015-05-18 15:32:47 IST+0530
I want to convert the current time to +0900 in Python ...
I don't want to change it on a server basis or globally, just in this one instance.
To get current time for +0900
timezone offset from UTC:
from datetime import datetime, timedelta
current_time_in_utc = datetime.utcnow()
result = current_time_in_utc + timedelta(hours=9)
Don't use aware datetime objects unless you also use pytz library otherwise you might get wrong results due to DST transitions and other timezone changes. If you need to do some arithmetics on datetime objects; convert them to UTC first.
You can use the datetime
module instead. Adapted from http://docs.python.org/library/datetime.html#datetime.tzinfo.fromutc
from datetime import tzinfo, timedelta, datetime
class FixedOffset(tzinfo):
def __init__(self, offset):
self.__offset = timedelta(hours=offset)
self.__dst = timedelta(hours=offset-1)
self.__name = ''
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return self.__dst
print datetime.now()
print datetime.now(FixedOffset(9))
Gives:
2011-03-12 00:28:32.214000
2011-03-12 14:28:32.215000+09:00
When I run it (I'm UTC-0500 for another day, then DST begins)
Just in case you can use pytz and other external modules, this is a more straight forward solution
pip install pytz tzlocal
then
from datetime import datetime
from pytz import timezone
import pytz
from tzlocal import get_localzone
#timezones
local = get_localzone()
utc = pytz.utc
cet = timezone('CET')
#get now time in different zones
print(datetime.now(local))
print(datetime.now(cet))
print(datetime.now(utc))
#convert local time now to CET
print(datetime.now(local).astimezone(cet))
print(datetime.now(cet).astimezone(utc))
In the datetime
module, there is an abstract base class called tzinfo
which controls how datetime.datetime
and datetime.time
handle time zones. You basically derive your own class to control the time zone interpretation. I have never personally used it, so I can't say much more about it.
Unfortunately, the only time zone controls I see directly in the time
module work on a global basis, I believe.
精彩评论