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


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

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

Pythonには日付や日時を扱うdatetimeモジュールがありますが、日付の取得・計算にはtimedeltaを使います。

開発環境

Python 3.8.0

現在の日付、時刻を取得

import datetime

now = datetime.datetime.now()

print(now)
2020-11-02 17:17:43.072607

日付の計算(足し算)

明日

import datetime

now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)

print(tomorrow)
2020-11-03 17:17:43.072607

一週間後

import datetime

now = datetime.datetime.now()
next_week = now + datetime.timedelta(weeks=1)

print(next_week)
2020-11-09 17:17:43.072607

日付+時間の計算は引数を追加します。

import datetime

now = datetime.datetime.now()
dt1 = now + datetime.timedelta(days=4, hours=3)

print(dt1)
2020-11-06 20:17:43.072607

日付の計算(引き算)

5日前

import datetime

now = datetime.datetime.now()
five_days_ago = now - datetime.timedelta(days=5)

print(five_days_ago)
2020-10-28 17:17:43.072607

3週間前

import datetime

now = datetime.datetime.now()
three_weeks_ago = now - datetime.timedelta(weeks=3)

print(three_weeks_ago)
2020-10-12 17:17:43.072607

週+日の計算は引数を追加します。

import datetime

now = datetime.datetime.now()
dt2 = now - datetime.timedelta(weeks=1, days=5)

print(dt2)
2020-10-21 17:17:43.072607

補足

datetime.timedeltaの引数を指定して日、時間、分、秒、ミリ秒、マイクロ秒後に計算できます。

weeks週
days日
hours時間
minutes分
seconds秒
millisecondsミリ秒
microsecondsマイクロ秒

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


人気のタグ

Alembic API argparse Beautiful Soup black Channels Cloud9 CodeCommit CodePipeline datetime Django REST framework Docker enumerate f-string git GitHub glob i18n IAM Internship Jupyter Lambda Matplotlib Nginx openai OpenCV pandas PIL Pillow PostgreSQL PyCharm pyenv PyTorch Rembg requests S3 Sentry slack tqdm Twitter uWSGI venv Vue.js WordPress youtube


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

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




    Show Comments (0)

    Comments

    Related Articles

    Python

    Pythonのargparseでコマンドライン引数をパース

    Pythonのargparseでコマンドライン引数をパース argparseモジュールを使って、Pythonを実行する際にコマンドライン引数を指定してプログラム内に情報を渡す方法です。 引数によって処理を変えたり、別々の […]

    Posted on by press
    Python

    PillowでPNGファイルを変換するときの背景処理

    PillowでPNGファイルを変換するときの背景処理 PillowでPNGファイルをJPGに変換するときに、背景が透過のファイルを変換すると透過部分が黒くなったり、不自然な途切れ方をしたりといった時の対処方法です。 開発 […]

    Posted on by press