Friday, March 21, 2014

File Location of Running Python Script

Problem : During development phase I was saving files with file.open("filename"), for this the python interpretor tries and search the file in the directory where the script is located.  For the development part this was good but once deployed to production and where  corntab script was suppose to execute it , the interpretor was not looking for these files in the directory of the script resulting in code break.

Solution: Instead of absolute file names or path provide path relative to the script or python file that is running


  1. Get Path of the directory where current python script is running
  2. import os
  3. filepath  = os.path.dirname(os.path.realpath(__file__)) + "/"+"filename"
  4. Now the file path will have the file you want to open
  5. file = open(filepath)
And with this we are good to go !


Timezone Conversion in Python

Problem : We have an application where timezone is not saved and only timestamp is stored.  Problem arises when one tries to convert UTC timezone to local timezone and then converting it to time stamp . To be stored in Timezone Agnostic database.

Solution :

  1. import iso8601 module
  2. timestamp_iso8601_string = '2014-03-18T04:19:05-00:00'
  3. tz_aware_date = iso8601.parse_date(timestamp_iso8601_string)
  4. import pytz
  5. ist_timezone =pytz.timezone('YOUR TIMEZONE')
  6. your_localtimewithout_tz = tz_aware_date.astimezone(ist_timezone).replace(tzinfo=None)
  7. your_localtimewithout_str = str(your_localtimewithout_tz)
This will do the required conversion. And we are good to go.