Python:将本地时间转换为另一个时区 [英] Python: Convert local time to another time zone

查看:40
本文介绍了Python:将本地时间转换为另一个时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 中将当前时间转换为 +0900.

I want to convert the current time to +0900 in Python.

执行此操作的合适方法是什么(假设在时间模块中)?

What's the appropriate way to do this (assuming in the time module)?

我读过这不包含在 Python 中,你必须使用类似 pytz 的东西.

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.

推荐答案

您可以使用 datetime 模块 代替.改编自 http://docs.python.org/library/datetime.html#datetime.tzinfo.来自utc

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))

给出:

2011-03-12 00:28:32.214000
2011-03-12 14:28:32.215000+09:00

当我运行它时(另一天我是 UTC-0500,然后开始夏令时)

When I run it (I'm UTC-0500 for another day, then DST begins)

这篇关于Python:将本地时间转换为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆