Pythonのdatetimeで日付、時間の計算(2)


press
Pythonのdatetimeで日付、時間の計算(2)

Pythonのdatetimeで日付、時間の計算(2)

前回からの続きです。

今回は、曜日を取得したり、特定の曜日の日付を取得します。後半は文字列とdatetimeの変換について説明します。

開発環境

Python 3.8.0

本日の曜日を取得

import datetime

weekday = datetime.date.today().weekday()

print(weekday)
1

月曜日が「0」から始まるので「1」は火曜日になります。

import datetime
import calendar

weekday_name = calendar.day_name[datetime.date.today().weekday()]

print(weekday_name)
Tuesday

calendarモジュールを利用することで、文字列で曜日を取得できます。

今週の月曜日の日付けを取得

import datetime

today = datetime.date.today()
last_monday= today - datetime.timedelta(days=today.weekday())

print(last_monday)
2021-01-18

特定の日付けの曜日を取得

import datetime

date = datetime.date(2021, 1, 1)

print(date.strftime('%A'))
Friday

2021年1月1日の曜日を取得しました。「%A」とフォーマットを指定することで曜日を取得できます。

datetime, dateから文字列へ変換

import datetime

now = datetime.datetime.now()

now.strftime('%Y年%m月%d日')

now.strftime('%Y, %B %d, %A')
2021年01月19日

2021, January 19, Tuesday

文字列からdatetime, dateへ変換

import datetime

date_1 = '2021/01/01'

date_2 = '2020年6月10日'

date_3 = '2020-9-24 4:49:2'


datetime.datetime.strptime(date_1, '%Y/%m/%d')

datetime.datetime.strptime(date_2, '%Y年%m月%d日')

datetime.datetime.strptime(date_3, '%Y-%m-%d %H:%M:%S')
datetime.datetime(2021, 1, 1, 0, 0)

datetime.datetime(2020, 6, 10, 0, 0)

datetime.datetime(2020, 9, 24, 4, 49, 2)

当ブログは群馬県でPython / Djangoを中心にウェブアプリケーションを開発している株式会社ファントムが運営しています。


人気のタグ

Alembic API argparse Beautiful Soup black Channels charset ChromeDriver CodeCommit datetime Django REST framework Docker enumerate f-string git GitHub glob Google Colaboratory i18n Internship Jupyter Matplotlib Nginx OpenCV pandas PIL Pillow PostgreSQL PyCharm PyCon pyenv PyTorch Redis Rembg ReportLab requests S3 Selenium Sentry slack tqdm uWSGI venv Vue.js youtube


株式会社ファントムへのお問い合わせ

群馬県でPythonを使ったAIやソフトウェアを開発している株式会社ファントムが運営しています。




    Show Comments (0)

    Comments

    Related Articles

    Python

    UnicodeEncodeError: ‘ascii’ codec can’t encode

    UnicodeEncodeError: ‘ascii’ codec can’t encode Pythonのprint() 関数で文字列を出力する時に以下の様なUnicodeEncod […]

    Posted on by press
    Python

    Pythonのrandomモジュールでランダムな小数・整数を生成

    Pythonのrandomモジュールでランダムな小数・整数を生成 Pythonで乱数(ランダムな小数や整数)が生成できる、randomモジュールの使い方を説明します。 開発環境 float型の乱数を生成(1) float […]

    Posted on by press

    最新情報をお届けします!

    メーリングリストに登録するとファントムの最新情報をお届けします

    お客様のメールアドレスを共有することはありません