Python:timezone.localize() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15641898/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:36:17  来源:igfitidea点击:

Python: timezone.localize() not working

pythondatetimetimezone

提问by WorkerBee

I am having some issues getting timezone.localize()to work correctly. My goal is to grab today's date and convert it from CST to EST. Then finally format the datetime before spitting it out. I am able to format the date correctly, but the datetime is not changing from CST to EST. Additionally when I format the date I don't see the text representation of the timezone included.

我在timezone.localize()正常工作时遇到了一些问题。我的目标是获取今天的日期并将其从 CST 转换为 EST。然后最后在吐出之前格式化日期时间。我能够正确格式化日期,但日期时间没有从 CST 更改为 EST。此外,当我格式化日期时,我看不到包含的时区的文本表示。

Below I have listed out a simple program I created to test this out:

下面我列出了我创建的一个简单的程序来测试这个:

#! /usr/bin/python
#Test script

import threading
import datetime
import pexpect
import pxssh
import threading
from pytz import timezone
import pytz

est = timezone('US/Eastern')
curtime = est.localize(datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y"))
#test time change
#curtime = datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y")

class ThreadClass(threading.Thread):
  def run(self):
    #now = (datetime.datetime.now() + datetime.timedelta(0, 3600))
    now = (datetime.datetime.now())
    print "%s says Hello World at time: %s" % (self.getName(), curtime)

for i in range(3):
  t = ThreadClass()
  t.start()

采纳答案by Martijn Pieters

.localize()takes a naive datetime object and interprets it as ifit is in that timezone. It does notmove the time to another timezone. A naive datetime object has notimezone information to be able to make that move possible.

.localize()接受一个简单的 datetime 对象并将其解释为就好像它在那个时区一样。它并没有时间移动到另一个时区。一个简单的 datetime 对象没有时区信息来实现这个移动。

You want to interpret now()in your localtimezone instead, then use .astimezone()to interpret the datetime in another timezone:

您想now()本地时区中.astimezone()进行解释,然后使用在另一个时区中解释日期时间:

est = timezone('US/Eastern')
cst = timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
est_curtime = curtime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y"))

def run(self):
    print "%s says Hello World at time: %s" % (self.getName(), est_curtime)

回答by unutbu

Use cst.localizeto make a naive datetime into a timezone-aware datetime.

用于cst.localize将原始日期时间转换为时区感知日期时间。

Then use astimezoneto convert a timezone-aware datetime to another timezone.

然后用于astimezone将时区感知日期时间转换为另一个时区。

import pytz
import datetime

est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
curtime = curtime.astimezone(est)