Python: timezone.localize() not working

前端 未结 2 1866
孤街浪徒
孤街浪徒 2021-01-07 22:13

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

2条回答
  •  旧巷少年郎
    2021-01-07 22:40

    .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.

    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)
    

提交回复
热议问题