Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convert iCalendar File (.ics) to new Timezone
#!/usr/bin/env python
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())
newtz = timezone(args.timezone)
except pytz.exceptions.UnknownTimeZoneError:
sys.exit('Invalid timezone; unable to update ics file.')
oldtz = timezone(cal.get('X-WR-TIMEZONE'))
for component in cal.walk():
if == 'VCALENDAR':
elif == 'VEVENT':
dtstart = component.get('DTSTART')
dtend = component.get('DTEND')
dtstamp = component.get('DTSTAMP')
dtstart.dt = oldtz.localize(dtstart.dt).astimezone(newtz)
dtend.dt = oldtz.localize(dtend.dt).astimezone(newtz)
dtstamp.dt = oldtz.localize(dtstamp.dt).astimezone(newtz)
open(args.file, 'wb').write(cal.to_ical())
Copy link

ParagDoke commented Aug 6, 2017

Thank you for this !
Modified just a bit for aware datetime objects:

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