A Python program that converts ical data into text

The data exported from the OS X calendar and Google Calendar is in ical format, but it is a bit inconvenient to view it even if it is saved as it is as a past record, so a text file with the date and time and the event name on one line I wanted to keep it. I searched the net and found the icalendar package for Python.

Icalendar library package for Python

Download the package that handles the ical format in Python from the following site.

https://pypi.python.org/pypi/icalendar

At the time I downloaded it, it was icalendar 3.10 and it supports Python 2.6, 2.7 and 3.3+.

Package installation

Unzip the .zip file downloaded from the above, move to that folder in the terminal, and install with the following command.

$ python setup.py install



## A program that retrieves events from ical data
 The Python program that reads an ical format file and outputs it to standard output is as follows.

 The usage is as follows


#### **`$ python iCal2txt.py file | sort > output file`**
```py file | sort > output file


 Example of use: `` `$ python iCal2txt.py yotei2016.ical | sort> calendar2016.txt` ``
 Now, "calendar2016.txt" is output as text data that extracts the date and time and event name from the data of "yotei2016.ical" and sorts them in order of date and time.

 The Python program source is as follows


#### **`iCal2txt.py`**
```python

#!/usr/bin/python
# -*- coding: utf-8 -*-

import codecs
import sys
from icalendar import Calendar, Event
from datetime import datetime

argvs = sys.argv
fin = codecs.open(argvs[1])
cal = Calendar.from_ical(fin.read())
body = ""
for ev in cal.walk():
    if ev.name == 'VEVENT':
        start_dt = ev.decoded("dtstart")
        end_dt = ev.decoded("dtend")
        summary = ev['summary'].encode('utf-8')
        print "{start} - {end} : {summary}".format(start=start_dt.strftime("%Y/%m/%d %H:%M"), end=end_dt.strftime("%Y/%m/%d %H:%M"), summary=summary)
        

What time was that event with this file? It is easy to find out.

I used to write a script that retrieves a similar file from an iCal app with AppleScript, but writing it in Python is pretty easy and I like Python. (Because there was a package)

(Addition) Output to a file with the extension of the input file name as .txt

If sorting is not necessary, it is troublesome to specify the output file, so I changed the extension to .txt in the input file name and output it.

ical2txt2.py


#!/usr/bin/python
# -*- coding: utf-8 -*-

import codecs
import os
import sys
from icalendar import Calendar, Event
from datetime import datetime

argvs = sys.argv
fin = codecs.open(argvs[1])
cal = Calendar.from_ical(fin.read())
fin.close()
ldata = ""
for ev in cal.walk():
    if ev.name == 'VEVENT':
        start_dt = ev.decoded("dtstart")
        end_dt = ev.decoded("dtend")
        summary = ev['summary'].encode('utf-8')
        ldata += "{start} - {end} : {summary}".format(start=start_dt.strftime("%Y/%m/%d %H:%M"), end=end_dt.strftime("%Y/%m/%d %H:%M"), summary=summary) + os.linesep
fname,ext = (sys.argv[1]).split(".",1)
fout = fname + ".txt"
f = codecs.open(fout, "w")
f.write(ldata)
f.close()

(Addition 2) Output the sorted result to a .txt file

When sorting in the program, the characters were garbled, so I tried to output before sorting as described above, but I was able to eliminate the garbled characters. The source is as follows. Change the line feed code of the output according to your environment. (Since the behavior of os.linesep was strange, the line feed code is specified directly.)

Example of use: `$ python ical2txt.py yotei2016.ics`

ical2txt3.py


#!/usr/bin/python
# -*- coding: utf-8 -*-

import codecs
import os
import sys
from icalendar import Calendar, Event
from datetime import datetime

argvs = sys.argv
fin = codecs.open(argvs[1])
cal = Calendar.from_ical(fin.read())
fin.close()
li = []
for ev in cal.walk():
    if ev.name == 'VEVENT':
        start_dt = ev.decoded("dtstart")
        end_dt = ev.decoded("dtend")
        summary = ev['summary'].encode('utf-8')
        li.append("{start} - {end} : {summary}".format(start=start_dt.strftime("%Y/%m/%d %H:%M"), end=end_dt.strftime("%Y/%m/%d %H:%M"), summary=summary).decode('utf-8'))
li.sort()
fname,ext = (sys.argv[1]).split(".",1)
fout = fname + ".txt"
f = codecs.open(fout, "w")
for ld in li:
    f.write(ld.encode('utf-8') + "\n")
f.close()

Recommended Posts

A Python program that converts ical data into text
A Python program that aggregates time usage from icalendar data
A python script that converts Oracle Database data to csv
[Python] A program that rounds the score
A python program that resizes a video and turns it into an image
A program that removes duplicate statements in Python
A site that converts curl commands into requests
[Python] A program that counts the number of valleys
Receive dictionary data from a Python program in AppleScript
Python that merges a lot of excel into one excel
Until you insert data into a spreadsheet in Python
A server that echoes data POSTed with flask / python
[Python] A convenient library that converts kanji to hiragana
[Python] A program that compares the positions of kangaroos.
A program that summarizes the transaction history csv data of SBI SECURITIES stocks [Python3]
I made a python text
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python
A function that divides iterable into N pieces in Python
Published a library that hides character data in Python images
A program that removes specific characters from the entered text
AnimeGAN Yaru (Windows10, Python3.6) that converts live-action into anime style
White-box Cartoonization that converts live-action into anime style (Windows10, Python3.6)
I tried "a program that removes duplicate statements in Python"
[Python] A program that creates a two-dimensional array by combining integers
[Python] A program that finds the most common bird types
[Python] A story that seemed to fall into a rounding trap
[Ev3dev] Create a program that captures the LCD (screen) using python
A program that determines whether a number entered in Python is a prime number
Map Creator, a service that converts latitude and history into URLs
[Python algorithm] A program that outputs Sudoku answers from a depth-first search
When writing a program in Python
[Python] A program that rotates the contents of the list to the left
I made a web application that converts photos into Van Gogh's style
[Python] A program that finds a pair that can be divided by a specified value
I made a web application in Python that converts Markdown to HTML
[Python] A program that calculates the number of socks to be paired
A summary of Python e-books that are useful for free-to-read data analysis
Created Simple SQLite, a Python library that simplifies SQLite table creation / data insertion
Code reading of faker, a library that generates test data in Python
I made a payroll program in Python!
Add a Python data source with Redash
Python3 + pyperclip that rewrites the copied text
Write a Caesar cipher program in Python
[Python] Create a LineBot that runs regularly
A typed world that begins with Python
I made a program in Python that reads CSV data of FX and creates a large amount of chart images
[Python, PyPDF2] A script that divides a spread PDF into two left and right
[Beginner] What happens if I write a program that runs in php in Python?
Format DataFrame data with Pytorch into a form that can be trained with NN
I want to exe and distribute a program that resizes images Python3 + pyinstaller
[Python] A program that finds the minimum and maximum values without using methods
[Python] A program that calculates the difference between the total numbers on the diagonal line.
[Python] A program that calculates the number of updates of the highest and lowest records
Create a web app that converts PDF to text using Flask and PyPDF2
A program that sends a fixed amount of mail at a specified time by Python
A script that converts between Django language files (PO) and tab-separated text (TSV)
I made a Python program for Raspberry Pi that operates Omron's environmental sensor in the mode with data storage
Create test data like that with Python (Part 1)
A memo that I wrote a quicksort in Python
[Python / Tkinter] A class that creates a scrollable Frame