Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: timezone.localize() not working

Tags:

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() 
like image 755
WorkerBee Avatar asked Mar 26 '13 16:03

WorkerBee


People also ask

How do I get local time zone in Python?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.

How do you add timezone in Python?

You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.

What is localize in Python?

Localization in Python refers to the process of adapting a Python-based application. The primary way of implementing localization in Python is through GNU Gettext, a third-party library designed to streamline the text extraction and translation from code.


1 Answers

.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) 
like image 90
Martijn Pieters Avatar answered Sep 21 '22 06:09

Martijn Pieters