Pythonにおける実用的なコードスニペット集

時刻をミリ秒に変換する方法

from datetime import datetime
import time

def timestamp_to_formatted(timestamp):
    dt = datetime.fromtimestamp(float(timestamp))
    return dt.strftime('%H:%M:%S.%f')

def time_str_to_ms(time_str):
    hours, mins, secs_ns = time_str.split(':')
    secs, ns = secs_ns.split('.')
    total_ms = (int(hours)*3600 + int(mins)*60 + int(secs))*1000 + int(ns)/1000
    return total_ms

current_ms = time_str_to_ms(timestamp_to_formatted(time.time()))
print(current_ms)

OSモジュールの基本操作

import os
current_dir = os.getcwd()  # カレントディレクトリ取得

例外処理の実装例

def validate_length():
    raise ValueError("入力テキストが長すぎます")

try:
    validate_length()
except ValueError as err:
    print(f"エラー発生: {err}")
except TypeError:
    pass
except Exception:
    pass

データクラスの活用

from dataclasses import dataclass

@dataclass
class UserProfile:
    username: str
    age: int
    location: str
    
    @classmethod
    def create_default(cls):
        return cls("guest", 0, "unknown")

user = UserProfile("taro", 30, "Tokyo")
print(user)

シェルコマンド実行

import os
os.system('dir')  # Windows環境の場合

ファイル操作

lines = []
with open('data.txt', 'r', encoding='utf-8') as f:
    for line in f:
        lines.append(line.strip())

JSONデータ処理

import json

# ファイルから読み込み
with open('config.json') as f:
    config = json.load(f)

# 文字列から変換
json_str = '{"id": 100, "name": "商品A"}'
item = json.loads(json_str)

キーワード引数の強制

def process_data(*, input_path, output_dir, verbose=False):
    print(f"入力: {input_path}, 出力: {output_dir}")

# 呼び出し例(キーワード引数必須)
process_data(input_path="data.csv", output_dir="./results")

ローカルパッケージインストール

pip download -d ./packages requests
pip install --no-index --find-links=./packages requests

データセット作成

from datasets import Dataset
import pandas as pd

df = pd.DataFrame({
    'question': ["質問1", "質問2"],
    'answer': ["回答1", "回答2"]
})

dataset = Dataset.from_pandas(df)
dataset.save_to_disk('qa_dataset')

リスト操作

scores = [85, 90, 78, 92]
avg_score = sum(scores)/len(scores)
print(f"平均点: {avg_score:.1f}")

タグ: Python datetime dataclass JSON 例外処理

6月8日 18:19 投稿