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 charset CodeCommit datetime Django REST framework Docker enumerate f-string git GitHub glob Google Colaboratory i18n IAM Internship Jupyter Lambda Matplotlib Nginx OpenCV pandas PIL Pillow PostgreSQL PyCharm PyCon pyenv PyTorch Redis Rembg ReportLab requests S3 Sentry slack tqdm uWSGI venv Vue.js youtube


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

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




    Show Comments (0)

    Comments

    Related Articles

    Python

    Pythonのf文字列を使った書式パターン

    Pythonのf文字列を使った書式パターン この記事で紹介したf文字列を使った文字列の操作ですが、文字列に変数を埋め込む際に書式を指定できます。0埋めして文字数を揃えたり、カンマで桁を区切ることも可能です。 カンマで桁区 […]

    Posted on by press
    Python

    OpenCVで画像から輪郭を上手く抽出する

    pythonのOpenCVで輪郭を上手く抽出することができなかったが、いくつかの改善点により上手く行った経緯をここに書き残しておく。 改善前 これは50×50のスカートの画像である。単にfindcontourし […]

    Posted on by EIGHT