Alex Rivera | Logout

Python: Convert local time to another time zone

Asked 2011-03-12T05:06:04.417
20

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 use something like pytz.

I don't want to change it on a server basis or globally, just in this one instance.

Edit
Report

2 Answers

11

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)

answered 2011-03-12T05:28:35.703
0

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.

answered 2011-03-12T05:23:00.943

Your Answer