A Python program that aggregates time usage from icalendar data

Package installation

First, pip install icalendar is.

Next, create the items to be used for analysis in Excel.

Meeting Material creation Email
Morning meeting Preparation of meeting materials Morning email check
Lunch meeting Report material creation Check your email during the day
Night meeting Night email check

Enter the item of the unit you want to analyze on the first line, and the sub-items of each analysis unit on the second and subsequent lines. This sub-item becomes the search keyword for iCalendar data.

I will also name it item table .xlsx and save it.

Next, prepare the icalendar data to be analyzed.

I think there are various ways to prepare. Exporting from Outlook is easy, isn't it?

Next is the source.

To be honest, I don't think it's elegant at all, but since I'm a beginner, please forgive me, or please give me some guidance.

-First read the item table and create a dataframe for data aggregation of the same size -One after another, icalendar data is read, the corresponding coordinates are found from the item table.xlsx, and the calculated time is added to the corresponding data frame for aggregation.

Waste of memory? I think there are many things like double loops are not elegant, so please comment.

import numpy as np
import pandas as pd
import icalendar as ic
from datetime import timedelta


def calculate_time(event):
    start = event['DTSTART'].dt
    end = event['DTEND'].dt

    time = end -start

    return time.total_seconds() / 3600


def main():
    labels = pd.read_excel('./Item list.xlsx')
    print(labels)

    file = open('./testdata.ics', 'r', encoding='utf-8')
    cal = ic.Calendar.from_ical(file.read())

    data = pd.DataFrame(np.zeros((labels.shape[0], labels.shape[1])))
    data.columns = label.columns

    for event in cal.walk('vevent'):
        time = calculate_time(event)
        summary = str(event.get('summary'))

        for i in range(0, labels.shape[0]):
            for j in range(0, labels.shape[1]):
                if str(labels.iloc[i, j]) in summary:
                    data.iloc[i, j] = data.iloc[i, j] + time


    print(data)

if __name__ == '__main__':
    main()

If you don't know what you are doing, please ask. I haven't graphed it yet, but at this point it should be easy to graph.

An example of graphing

I'll make it a pie chart.

data.sum().plot.pie(legend=False, autopct="%.1f%%", textprops={'fontproperties': fp, 'fontsize':20})
plt.axis('equal')

I try to display the percentage as autopct = "% .1f %%" so that legend = False does not cause annoying legends.

The point when using Japanese fonts was that it took time to find out how to write textprops = {'fontproperties': fp,'fontsize': 20}). I couldn't find any information on how to specify a Japanese font when using a pie chart with a python plot, and it took a long time.

plt.axis ('equal') prevents the pie chart from collapsing.

References

・ Https://gist.github.com/lukasmartinelli/9021795

Recommended Posts

A Python program that aggregates time usage from icalendar data
Receive dictionary data from a Python program in AppleScript
A Python program that converts ical data into text
A memo that reads data from dashDB with Python & Spark
[Python algorithm] A program that outputs Sudoku answers from a depth-first search
[Python] A program that creates stairs with #
A program that plays rock-paper-scissors using Python
[Python] A program that rounds the score
Get time series data from k-db.com in Python
A program that removes duplicate statements in Python
"Python Kit" that calls a Python script from Swift
Extract data from a web page with Python
A program that sends a fixed amount of mail at a specified time by Python
[Python] A program that counts the number of valleys
Features that can be extracted from time series data
Output the time from the time the program was started in python
From a book that programmers can learn ... (Python): Pointer
Created a Python library DateTimeRange that handles time ranges
From buying a computer to running a program with python
A server that echoes data POSTed with flask / python
[Python] A program that compares the positions of kangaroos.
A program that summarizes the transaction history csv data of SBI SECURITIES stocks [Python3]
"Getting stock price time series data from k-db.com with Python" Program environment creation memo
Predict from various data in Python using Facebook Prophet, a time series prediction tool
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python
Published a library that hides character data in Python images
From a book that programmers can learn ... (Python): About sorting
How to run a Python program from within a shell script
A program that removes specific characters from the entered text
python Condition extraction from a list that I often forget
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
I tried "a program that removes duplicate statements in Python"
[Python] A program that creates a two-dimensional array by combining integers
Library tsfresh that automatically extracts features from time series data
[Python] Plot time series data
[Python] A program that finds the most common bird types
A python script that converts Oracle Database data to csv
Create an API that returns data from a model using turicreate
[numpy] Create a moving window matrix from multidimensional time series data
From a book that programmers can learn (Python): Find the mode
From a book that programmers can learn ... (Python): Review of arrays
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Simple code to call a python program from Javascript on EC2
A function that measures the processing time of a method in python
[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
[Python] A program that rotates the contents of the list to the left
From a book that programmers can learn (Python): Statistical processing-deviation value
Call a Python function from p5.js.
Python: Exclude tags from html data
Touch a Python object from Elixir
Hit treasure data from Python Pandas
Python: Time Series Analysis: Preprocessing Time Series Data
Get data from Quandl in Python
python / Make a dict from a list.
When writing a program in Python
2. Make a decision tree from 0 with Python and understand it (2. Python program basics)
[Python] A program that calculates the number of chocolate segments that meet the conditions
[Python] A program that finds a pair that can be divided by a specified value
[Python] A program that calculates the number of socks to be paired