Python - 在特定时区设置日期时间(无UTC转换) [英] Python - Setting a datetime in a specific timezone (without UTC conversions)
问题描述
要清楚,这是python 2.6,我使用pytz。
Just to be clear, this is python 2.6, I am using pytz.
这是一个仅处理美国时区的应用程序,我需要能够锚定一个日期(今天),并获得一个unix时间戳(时代)晚上8点和晚上11点,只有PST。
This is for an application that only deals with US timezones, I need to be able to anchor a date (today), and get a unix timestamp (epoch time) for 8pm and 11pm in PST only.
这让我很疯狂。
> pacific = pytz.timezone("US/Pacific")
> datetime(2011,2,11,20,0,0,0,pacific)
datetime.datetime(2011, 2, 11, 20, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:0 STD>)
> datetime(2011,2,11,20,0,0,0,pacific).strftime("%s")
'1297454400'
zsh> date -d '@1297454400'
Fri Feb 11 12:00:00 PST 2011
所以,即使我正在设置一个时区,并且使用这个时区创建datetime ,它仍然是以UTC形式创建的,然后进行转换。这是一个更多的问题,因为当我尝试进行计算时,UTC将是一天。
So, even though I am setting up a timezone, and creating the datetime with that time zone, it is still creating it as UTC and then converting it. This is more of a problem since UTC will be a day ahead when I am trying to do the calculations.
是否有一个简单(或至少是感性的)生成方式今天晚上8点PST的时间戳记?
Is there an easy (or at least sensical) way to generate a timestamp for 8pm PST today?
(要清楚的是,我明白了在大多数情况下使用UTC的价值,如数据库时间戳或一般存储,不是这些情况之一,我特别需要PST的晚上时间戳,UTC不应该输入。)
(to be clear, I do understand the value of using UTC in most situations, like database timestamps, or for general storage. This is not one of those situations, I specifically need a timestamp for evening in PST, and UTC should not have to enter into it.)
推荐答案
p>为UTC时区创建一个tzinfo对象 utc
,然后尝试:
Create a tzinfo object utc
for the UTC time zone, then try this:
#XXX: WRONG (for any timezone with a non-fixed utc offset), DON'T DO IT
datetime(2011,2,11,20,0,0,0,pacific).astimezone(utc).strftime("%s")
编辑:在评论中指出,将时区放入 datetime
构造函数并不总是强大的。使用 pytz文档的首选方法是:
As pointed out in the comments, putting the timezone into the datetime
constructor isn't always robust. The preferred method using the pytz documentation would be:
#XXX: WRONG (unless your local timezone is UTC), DON'T DO IT
pacific.localize(datetime(2011,2,11,20,0,0,0)).astimezone(utc).strftime("%s")
这篇关于Python - 在特定时区设置日期时间(无UTC转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!