如何将日期时间从一个任意时区转换为另一个任意时区 [英] How to convert a datetime from one arbitrary timezone to another arbitrary timezone

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

问题描述

假设我在这样的请求中收到了一个任意的datetime对象,它可能来自任何可能的时区-我不知道是哪个时区. 例如,假装它来自东海岸

Let's say I receive an arbitrary datetime object in a request, like this, which could be coming from any possible timezone - I don't know which one. For the sake of example, pretend it comes from the East Coast

import pytz
from colander import iso8601
...
    ests1 = iso8601.parse_date('2016-04-01T00:00:00.0000-04:00')

假装ests1是其中的对象

pretend ests1 is the object that comes in

使用pytz,我可以对它的时区有所了解

Using pytz, I can find out a bit about it's timezone

    etz = ests1.timetz()  # 00:00:00-04:00
    etzi = ests1.tzinfo   # <FixedOffset '-04:00' datetime.timedelta(-1, 72000)>
    etzn = ests1.tzname() # '-04:00'  # EST
    edst = ests1.dst()    #  '0:00:00'

请注意,无论ests1是什么日期-dst()似乎总是返回相同的值

Note that no matter what date ests1 is - dst() always seems to return the same value

我想做这样的事情:

    psts1 = pytz.timezone(etzn
                     ).localize(dtime.datetime.fromtimestamp(ests1)
                     ).astimezone(pytz.timezone('US/Pacific'))

但这只会导致

UnknownTimeZoneError: '-04:00'

我也尝试过这个:

def convert_dt_to_pstz(dt):
    pstoffset = -25200 # -7 * 60 * 60   - but what about DST?  how do we tell which offset to use? -8 or -7
    return dt.astimezone(tzoffset(None,pstoffset)) # convert to PST

但是问题是我不知道如何确定是否需要针对夏令时调整日期.

But the problem with that is I don't know how to tell if the date needs to be adjusted for daylight savings time.

我也尝试过:

    utc_date = ests1.astimezone(pytz.utc)   # 2016-04-01T04:00:00+00:00
    ptz = pytz.timezone('US/Pacific')
    new_date = utc_date.replace(tzinfo=ptz) # 2016-04-01T04:00:00-07:53

但是看看new_date的奇怪结果:-07:53 ??

But look at the strange result for new_date: -07:53 ??

请注意,我无法使用与现在"或服务器位置相对应的任何信息,因为它可能在任何地方

Please note that I cannot use any information corresponding to "now" or the location of the server as it could be anywhere

推荐答案

要将时区感知的datetime对象转换为其他时区,请

To convert a timezone-aware datetime object into a different timezone, use datetime.astimezone() method:

pacific_time = ests1.astimezone(pytz.timezone('US/Pacific'))

通常, pytz文档建议致电pytz.timezone('US/Pacific').normalize()上的结果,但您在这里不需要它,因为ests1时区具有固定的utc偏移量.

In general, pytz docs recommend to call pytz.timezone('US/Pacific').normalize() on the result but you don't need it here because ests1 timezone has a fixed utc offset.

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

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