1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

標準ライブラリ入門:random / datetime【Day 20】

1
Last updated at Posted at 2025-12-19

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day20 の記事です。

標準ライブラリ入門:random / datetime

Python には便利な 標準ライブラリ が最初から用意されています。
今回は random(乱数1)と datetime(日付・時刻)の基本を紹介します。

1. random:乱数を扱う

■ ランダムな整数

import random

print(random.randint(1, 10))  # 1~10の整数をランダムに出力

■ ランダムにリストの要素を選ぶ

fruits = ["apple", "banana", "orange"]
print(random.choice(fruits))

■ リストをシャッフルする

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)

2. datetime:日付・時刻を扱う

■ 今日の日付・現在時刻

from datetime import datetime

now = datetime.now()
print(now)

■ 年・月・日・時・分・秒を取得

print(now.year)   # 年
print(now.month)  # 月
print(now.day)    # 日
print(now.hour)   # 時
print(now.minute) # 分
print(now.second) # 秒

■ 日付のフォーマット表示

print(now.strftime("%Y/%m/%d %H:%M:%S"))  # 2025/11/28 15:00:00

3. 使いどころ

  • random

    • ゲームでサイコロを振る
    • リストからランダムに選ぶ
    • シャッフルや抽選
  • datetime

    • 日付・時刻の表示
    • ファイル名に日付を入れる
    • 経過時間の計算

4. 今日のまとめ

  • Python 標準ライブラリはインポートするだけで使える
  • random:乱数・シャッフル・ランダム選択
  • datetime:現在時刻・日付取得・フォーマット表示
  • 日常のプログラムや簡単なツール作りで頻出

5. ミニ問題

Q1.
1~100の内一つの整数をランダムに出力するコードを書いてください。

Q2.
現在の日付を YYYY-MM-DD 形式で表示するコードを書いてください。

  1. 正確には疑似乱数ですが初心者向けのため説明は省略

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?