Python - 在特定时区设置日期时间(无 UTC 转换)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4974712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Setting a datetime in a specific timezone (without UTC conversions)
提问by liam
Just to be clear, this is python 2.6, I am using pytz.
需要明确的是,这是python 2.6,我使用的是pytz。
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.
这是针对仅处理美国时区的应用程序,我需要能够锚定日期(今天),并仅在 PST 的晚上 8 点和晚上 11 点获取 unix 时间戳(纪元时间)。
This is driving me crazy.
这真让我抓狂。
> 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
So, even though I am setting up a timezone, and creating the datetime withthat 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.
因此,即使我正在设置时区,并使用该时区创建日期时间,它仍然将其创建为 UTC,然后进行转换。这更像是一个问题,因为当我尝试进行计算时,UTC 将提前一天。
Is there an easy (or at least sensical) way to generate a timestamp for 8pm PST today?
是否有一种简单(或至少是合理的)方法来为今天太平洋标准时间晚上 8 点生成时间戳?
(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.)
(要明确的是,我确实理解在大多数情况下使用 UTC 的价值,例如数据库时间戳或一般存储。这不是其中一种情况,我特别需要 PST 晚上的时间戳,而 UTC 不应该进入其中。)
采纳答案by Mark Ransom
Create a tzinfo object utcfor the UTC time zone, then try this:
utc为 UTC 时区创建一个 tzinfo 对象,然后试试这个:
#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")
Edit:As pointed out in the comments, putting the timezone into the datetimeconstructor isn't always robust. The preferred method using the pytz documentationwould be:
编辑:正如评论中所指出的,将时区放入datetime构造函数并不总是健壮的。使用pytz 文档的首选方法是:
pacific.localize(datetime(2011,2,11,20,0,0,0)).astimezone(utc).strftime("%s")
Also note from the comments that strftime("%s")isn't reliable, it ignoresthe time zone information (even UTC) and assumes the time zone of the system it's running on. It relies on an underlying C library implementation and doesn't work at all on some systems (e.g. Windows).
另请注意,strftime("%s")从不可靠的评论中,它会忽略时区信息(甚至 UTC)并假定它运行的系统的时区。它依赖于底层的 C 库实现,并且在某些系统(例如 Windows)上根本不起作用。
回答by jfs
There are at least two issues:
至少有两个问题:
- you shouldn't pass a timezone with non-fixed UTC offset such as
"US/Pacific"as tzinfo parameter directly. You should usepytz.timezone("US/Pacific").localize()methodinstead .strftime('%s')is not portable, it ignores tzinfo, and it always uses the local timezone. Usedatetime.timestamp()or its analogs on older Python versionsinstead.
- 您不应该直接传递具有非固定 UTC 偏移量的时区,例如
"US/Pacific"tzinfo 参数。你应该使用pytz.timezone("US/Pacific").localize()方法,而不是 .strftime('%s')不可移植,它忽略 tzinfo,并且始终使用本地时区。在较旧的 Python 版本上使用datetime.timestamp()或其类似物。
To make a timezone-aware datetime in the given timezone:
要在给定的时区中创建时区感知日期时间:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone("US/Pacific")
aware = tz.localize(datetime(2011, 2, 11, 20), is_dst=None)
To get POSIX timestamp:
获取 POSIX 时间戳:
timestamp = (aware - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
(On Python 2.6, see totimestamp()function on how to emulate .total_seconds()method).
(在 Python 2.6 上,请参阅totimestamp()有关如何模拟.total_seconds()方法的函数)。

