アメグラ2号のブログ

1980年代後半の古き良きビデオゲームのほか、オッサンの個人的備忘録

python アゲハチョウ羽化予定日を作成

f:id:game-allergy:20210331143049p:plain

たいしたことはないけど、ちょっとしたことを表で作成できるのはありがたい。エクセルで作ればいいんじゃん?と思うかもしれないけど、日ごろpythonを触っているなら、こっちのほうが早い。何より嫁さんに見せるには表を画像にしたほうが良いし。

スクリプト(羽化予定日)

# ***********************************
# サナギになって**日後に羽化する
# 早見表を作成する
# ***********************************
# ===================================
# import
# ===================================
import pandas as pd
import matplotlib.pyplot as plt
import japanize_matplotlib
import datetime
import os

# ===================================
# function
# ===================================
# Create flag date
def FlagDate(StartDate,dt_needsanagi):
    dtFlag = StartDate + dt_needsanagi
    return dtFlag

# To DataFrame
def PdDataFrame(columName,result1):
    df = pd.DataFrame({columName:result1})

    # serial number(from 1 to ***)
    serial_num = pd.RangeIndex(start=1, stop=len(df.index) + 1, step=1)
    # column name
    df['No.'] = serial_num
    # Locate columns
    df = df.loc[:, ['No.', columName]]

    return df

# Create table
def PltTable(df,titleName):
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set(title= titleName)
    ax.axis('off')
    ax.axis('tight')

    ax.table(cellText=df.values,
             colLabels=df.columns,
             bbox=[0, 0, 1, 1],
             )

    return fig

# time stamp
def Timestamp():
    dt1 = datetime.datetime.now()
    dt2 = dt1.strftime('%Y_%m%d_%H%M_%S')
    return dt2

# save table image as jpg file(Weather info as table)
def SaveTablefig(fig,currentdir,timestamp,figName):
    fig.savefig(currentdir  + '/fig/' + timestamp + figName + "_.jpg")

# ==============================================
# data
# ==============================================
n1 = datetime.date(2020,4,24)
n2 = datetime.date(2020,4,25)
n3 = datetime.date(2020,4,28)
n4 = datetime.date(2020,4,28)
n5 = datetime.date(2020,4,28)
n6 = datetime.date(2020,4,29)
n7 = datetime.date(2020,4,30)
n8 = datetime.date(2020,4,30)

SanagiList = (
            n1, 
            n2,
            n3,
            n4,
            n5,
            n6,
            n7,
            n8
            )

# ===================================
# execution
# ===================================
# working time 
dt_needsanagi = datetime.timedelta(days = 12)

# result date
resultList=[]
for i in SanagiList:
    result = FlagDate(i,dt_needsanagi)
    resultList.append(result)

# pandas dataframe
columName = 'date'
df_sanagi = PdDataFrame(columName,SanagiList)
df_result = PdDataFrame(columName,resultList)

# ready for table
currentdir = os.getcwd()
timestamp = Timestamp()
tableName1 = 'サナギになった日'
tableName2 = '羽化予定日'

# matplot; create table and save data as jpg file
fig1 = PltTable(df_sanagi,tableName1)
SaveTablefig(fig1,currentdir,timestamp,tableName1)

fig2 = PltTable(df_result,tableName2)
SaveTablefig(fig2,currentdir,timestamp,tableName2)