Skip to content

Instantly share code, notes, and snippets.

@ParagDoke
Created August 6, 2017 09:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ParagDoke/2388d7311f11cab4fa5f5538fa694d0e to your computer and use it in GitHub Desktop.
Save ParagDoke/2388d7311f11cab4fa5f5538fa694d0e to your computer and use it in GitHub Desktop.
Convert ics files with aware datetimes to new timezone
#!/usr/bin/env python
# vim:filetype=python:expandtab:tabstop=4:shiftwidth=4:
"""
Copied from https://gist.github.com/deybhayden/1980583#file-convert_ics_timezone-py
I observed that dtstart.dt datetime objects were aware (not naive).
There was no need to identify oldtz. Original author's comments left below.
Parag Doke
Asia/Kolkata :-)
-----
Simple script that updates all events in an ical file to a new timezone.
Requires icalendar package (which pulls in pytz as a dependency).
By: @beardedprojamz (Ben Hayden)
"""
import argparse
import sys
import pytz
from icalendar import Calendar
from pytz import timezone
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A script to convert an ics calendar & events to the passed timezone.')
parser.add_argument("--file", "-f", dest='file', help='The ics file to parse and update.', required=True)
parser.add_argument("--timezone", "-t", dest='timezone', help='The timezone used to update the ics file', required=True)
args = parser.parse_args()
cal = Calendar.from_ical(open(args.file, 'rb').read())
try:
newtz = timezone(args.timezone)
except pytz.exceptions.UnknownTimeZoneError:
sys.exit('Invalid timezone; unable to update ics file.')
for component in cal.walk():
if component.name == 'VEVENT':
dtstart = component.get('DTSTART')
dtend = component.get('DTEND')
dtstamp = component.get('DTSTAMP')
dtstart.dt = dtstart.dt.astimezone(newtz)
dtend.dt = dtend.dt.astimezone(newtz)
dtstamp.dt = dtstamp.dt.astimezone(newtz)
open(args.file, 'wb').write(cal.to_ical())
@thadk
Copy link

thadk commented Oct 4, 2020

Thanks! I had to specify an unexpected timezone to get it to do what I wanted but eventually this helped me fix the inaccurately always-UTC-based ics ical export from AirTable's calendar view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment