WorkerBee
WorkerBee

Reputation: 693

Python: timezone.localize() not working

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

Upvotes: 31

Views: 64186

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

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

Upvotes: 48

unutbu
unutbu

Reputation: 879083

Use cst.localize to make a naive datetime into a timezone-aware datetime.

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

import pytz
import datetime

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

Upvotes: 23

Related Questions