Created
March 5, 2012 19:45
-
-
Save deybhayden/1980583 to your computer and use it in GitHub Desktop.
Convert iCalendar File (.ics) to new Timezone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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()) | |
try: | |
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 component.name == 'VCALENDAR': | |
component.set('X-WR-TIMEZONE', newtz.zone) | |
elif component.name == '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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this !
Modified just a bit for aware datetime objects: https://gist.github.com/ParagDoke/2388d7311f11cab4fa5f5538fa694d0e