Python:timezone.localize()无法正常工作 [英] Python: timezone.localize() not working

查看:131
本文介绍了Python:timezone.localize()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

下面,我列出了我创建的一个简单程序来对此进行测试:

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()


推荐答案

.localize()需要一个简单的日期时间对象,并将其解释为在该时区。它不会将时间移到另一个时区。朴素的datetime对象没有 no 时区信息,因此无法移动。

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

您现在要解释 ()在您的 local 时区中,然后使用 .astimezone()解释另一个时区中的日期时间:

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

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)

这篇关于Python:timezone.localize()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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