Converting time from GMT to another timezone

Ben Hutchings do-not-spam-ben.hutchings at businesswebsoftware.com
Wed Mar 26 05:57:07 EST 2003


In article <m3el4z63uf.fsf at telia.com>, Andrew Markebo wrote:
> / Jp Calderone <exarkun at intarweb.us> wrote:
>| [...]
>|     import time
>|     now_EST = time.time() - 18000
>|     print time.asctime(time.gmtime(now_EST))

That's a terrible abuse of the gmtime() function.

> Just being interested, these 18000, is it possible to find out how
> much that is? I mean.. make a general python code that can show me the
> time difference between EST and CET? 

It depends on the time of year.

> Or is it something I as developer has to look up and hardcode into my
> code?

Please don't do that.

The best solution I can think of, within what Python provides, is
something like this:

    import sys, time

    def time_zone_convert(tm, source_zone, dest_zone):
        '''Convert a broken-down time (time.struct_time or tuple) from
        one named time zone to another.'''
        old_zone = sys.environ['TZ']
        try:
            sys.environ['TZ'] = source_zone
            stamp = time.mktime(tm)
            sys.environ['TZ'] = dest_zone
            return time.localtime(stamp)
        finally:
            sys.environ['TZ'] = old_zone

Unfortunately time zone names are not portable!  You would need to use
different names depending on the platform.




More information about the Python-list mailing list