Python:如何将时区知道时间戳转换为UTC,而不知道DST是否生效 [英] Python: How to convert a timezone aware timestamp to UTC without knowing if DST is in effect

查看:193
本文介绍了Python:如何将时区知道时间戳转换为UTC,而不知道DST是否生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将始终在太平洋时间的天真时间戳转换为UTC时间。在下面的代码中,我可以指定我在太平洋时间这个时间戳,但似乎不知道它应该是UTC的-7小时的偏移量,因为它只有10/21,DST有尚未结束。

I am trying to convert a naive timestamp that is always in Pacific time to UTC time. In the code below, I'm able to specify that this timestamp I have is in Pacific time, but it doesn't seem to know that it should be an offset of -7 hours from UTC because it's only 10/21 and DST has not yet ended.

脚本:

import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = naive_date.replace(tzinfo=localtz)
print date_aware_la

输出:

    2013-10-21 08:44:08-08:00

它应该有一个-07:00的偏移量,直到DST在11月3日结束。当DST不生效时,如何让我的时区知道日期有正确的偏移? pytz智能足以知道DST将在11月3日生效?

It should have an offset of -07:00 until DST ends on Nov. 3rd. How can I get my timezone aware date to have the correct offset when DST is and is not in effect? Is pytz smart enough to know that DST will be in effect on Nov 3rd?

总体目标:我只是想将时间戳转换为UTC,知道我将会在太平洋时间获得时间戳,无需指示DST是否有效。我没有从python本身生成这个日期,所以我不能使用utc_now()。

Overall goal: I'm just trying to convert the timestamp to UTC knowing that I will be getting a timestamp in pacific time without any indication whether or not DST is in effect. I'm not generating this date from python itself, so I'm not able to just use utc_now().

推荐答案

使用 localize 方法:

import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = localtz.localize(naive_date)
print(date_aware_la)   # 2013-10-21 08:44:08-07:00

这在 pytz文档

然后继续UTC:

utc_date = date_aware_la.astimezone(pytz.utc)
print(utc_date)

这篇关于Python:如何将时区知道时间戳转换为UTC,而不知道DST是否生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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