Question

I have a file that I check it's creation time using ctime. Here is the snippet of code (not complete, just the important part):

import time
import pytz
import os
from datetime import datetime

myfile = SOMEWHERE

myfile_ctime = os.path.getctime(myfile)
d = datetime.strptime(time.ctime(myfile_ctime), '%a %b %d %H:%M:%S %Y')
# d here is Tue Mar 25 00:33:40 2014 for example
ny = pytz.timezone("America/New_York")
d_ny = ny.localize(d)
mytz = pytz.timezone(MY_TZ_WHATEVER)
myd = d_ny.astimezone(mytz)
final_date = myd.strftime('%Y-%m-%d %H:%M:%S')
print(final_date + "some string") 
# is now 2014-03-25 01:33:40some string, correctly with the timezone.

When this is run as a simple python script, everything is ok. But when I run the same code inside a function in a templatetags/myfile.py that renders to a template in a Django App, when trying to get the date from time.ctime(myfile_ctime), then I get Tue Mar 25 04:33:40 instead of Tue Mar 25 00:33:40 from the snippet above (the code is the same in the standalone script and in Django - and I concatenate the date with another string).

My question is: I'm using just Python standard libraries, same snippet of code in both places, reading the same file in the same environment. Why the difference? Do settings in settings.py mangles up something in the standard libraries? Just being in a Django environment it changes how standard libraries should work? Why when calling standalone everything works as it should?

(I'm behind apache, don't know if this is relevant)

Was it helpful?

Solution 2

In ./django/conf/__init__.py:126:, TZ environment variable is set based on settings.py.

os.environ['TZ'] = self.TIME_ZONE

My TIME_ZONE is UTC.

That's why a standalone script result is different from a snippet inside Django: when running standalone, this environment variable TZisn't set.

Now, when creating a datetime object from a myfile_ctime, I just need to add tzinfo from my server (/etc/sysconfig/clock). My code now looks like this:

import time
import pytz
import os
from datetime import datetime

myfile = SOMEWHERE

myfile_ctime = os.path.getctime(myfile)

ny = pytz.timezone("America/New_York")
d = datetime.fromtimestamp(myfile_ctime, tz=ny)
mytz = pytz.timezone(MY_TZ_WHATEVER)
myd = d.astimezone(mytz)
final_date = myd.strftime('%Y-%m-%d %H:%M:%S')

I hope this is useful to someone. As always, read the source. :)

OTHER TIPS

Make sure of the Time Zone settings in settings.py, for more info about Django Time Zone Settings, check this page: https://docs.djangoproject.com/en/1.6/ref/settings/#time-zone

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top