Friday, March 21, 2014

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.

No comments:

Post a Comment