Python Datetime: 例を含む包括的なガイド

Python Datetime: 例を含む包括的なガイド

Python でデータ プロジェクトを操作する場合、日時関数を使用する可能性が最も高くなります。操作するほぼすべてのデータセットには、ニーズやプロジェクトの要件に応じて操作する日時列が含まれています。

幸いなことに、Python にはdatetimeという名前の独自の組み込みモジュールが付属しており、これを使用すると、日付、時刻、およびその 2 つの組み合わせなどの datetime インスタンスを表現、操作、および操作できます。Python datetime モジュールをマスターすると、プロジェクトでより堅牢な時系列分析を行うことができます。

Python datetime モジュールは、日付、時刻、および時間間隔を処理するためのツールです。日付や時刻に関するさまざまな操作を簡単に実行できます。

Python Datetime: 例を含む包括的なガイド

プログラミング概要 – ソフトウェア開発者が表示するソース コードとバイナリ コード。色付きの構文を備えた黒のテーマ。

Pythonの datetime モジュールを使用すると、日付と時刻の値の操作、タイム ゾーンの管理、計算の実行、さらにはさまざまな表現の書式設定や解析を簡単に行うことができます。この機能により、datetime モジュールは、データ処理からイベント スケジューリングなどの多くのアプリケーションにおいて不可欠なツールになります。

プロジェクトで Python の datetime モジュールの使用を開始する前に、その基礎となるクラスを理解することが重要です。以下のセクションでは、Python の DateTime モジュールの 5 つの主要なクラスを見ていきます。さあ、始めましょう!

目次

Python Datetime モジュールの 5 つの主要なクラスとは何ですか?

Python Datetime モジュールは、日付、時刻、タイムゾーン、および期間を操作および操作するためのクラスを提供する標準ライブラリの一部です。

このモジュールは 5 つの主要なクラスで構成されます。

  1. 日付時刻

  2. 日にち、

  3. 時間、

  4. タイムデルタ

  5. タイムゾーン。

    概念をより深く理解できるように、各クラスを見てからユースケースの例を見ていきます。

Datetime クラスの使用方法

Python Datetime クラスは、モジュール内で最もよく使用されるクラスです。これは、年、月、日、時、分、秒、マイクロ秒などの属性を持つ単一の時点を表します。

Python Datetime クラスの一般的な操作には次のようなものがあります。

  • datetime.datetime.now()

この関数を使用すると、現在の日付と時刻を取得できます。以下は、現在の日付と時刻を取得する例です。

import datetime

# Get the current date and time
now = datetime.datetime.now()

print("Current date and time: ", now)

これにより、実行時の現在の日付と時刻が YYYY-MM-DD HH:MM:SS.ssssss の形式で出力されます。

Python Datetime: 例を含む包括的なガイド

  • 日時.日時

この関数を使用すると、カスタムの日付と時刻オブジェクトを作成できます。以下は、コード内で datetime.datetime を使用する例です。

from datetime import date

# Create a custom date and time object
custom_date = datetime.datetime(2023, 5, 22, 17, 40)

print("Custom date and time: ", custom_date)

上記の関数に加えて、Datetime クラスは、次のような日付と時刻を操作するためのメソッドも提供します。

Python Datetime: 例を含む包括的なガイド

  • strftime() :

このメソッドを使用すると、日付と時刻のオブジェクトを文字列としてフォーマットできます。以下は strftime() メソッドの例です。

import datetime

# Create a custom date and time object
custom_date = datetime.datetime(2023, 5, 22, 17, 40)

# Format the datetime object as a string
formatted_date = custom_date.strftime("%B %d, %Y, %H:%M")

print("Formatted date and time: ", formatted_date)

このコードは日時オブジェクトを文字列に変換します。

Python Datetime: 例を含む包括的なガイド

  • strptime() :

datetime クラスのこの関数を使用すると、日付と時刻のオブジェクトを表す文字列を単一の Datetime オブジェクトに解析できます。以下は、文字列として格納された日付を Datetime オブジェクトに解析する例です。

import datetime

# String representing a date and time
date_string = "May 22, 2023, 17:40"

# Parse the string into a datetime object
parsed_date = datetime.datetime.strptime(date_string, "%B %d, %Y, %H:%M")

print("Parsed date and time: ", parsed_date)

これにより、文字列が DateTime オブジェクトに変換されます。

Python Datetime: 例を含む包括的なガイド

日付クラスの使用方法

Date クラスを使用すると、日付オブジェクト (年、月、日) のみを扱うことができます。date クラスを使用して日付オブジェクトを作成できます。

Date クラスの一般的な操作には次のようなものがあります。

  • datetime.date.today()

date クラスのこの関数を使用すると、現在の日付を取得できます。以下は、日付クラスを使用して現在の日付を取得する例です。

import datetime

# Get the current date
today = datetime.date.today()

print("Today's date: ", today)

この Python コードは、実行時の現在の日付を YYYY-MM-DD の形式で出力します。

Python Datetime: 例を含む包括的なガイド

この記事の執筆時点では、現在の日付は 2023-05-22 です。

  • 日付時刻.日付()

日付クラスのこの関数を使用すると、日付オブジェクトを作成できます。この例では、datetime.date() 関数を使用してカスタム日付オブジェクトを作成する方法を示します。

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

print("Custom date: ", custom_date)

datetime.date() 関数では、年、月、日を引数として指定します。

2023 年 5 月 22 日という日付のカスタム日付オブジェクトを作成したため、このスクリプトは 2023-05-22 を出力します。

Python Datetime: 例を含む包括的なガイド

Date クラスは、次のような便利なメソッドも提供します。

  • 平日()

date クラスのこのメソッドは、曜日 (月曜日の場合は 0、火曜日の場合は 1 など) を返します。次の例は、weekday() メソッドを示しています。

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Get the day of the week
day_of_week = custom_date.weekday()

print("Day of the week: ", day_of_week)

この例では、2023 年 5 月 22 日が月曜日に当たるため、custom_date.weekday() は 0 を返します。

Python Datetime: 例を含む包括的なガイド

  • strftime()

date クラスのこのメソッドを使用すると、日付オブジェクトを文字列としてフォーマットできます。次の例は、strftime() 関数を示しています。

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Format the date object as a string
formatted_date = custom_date.strftime("%B %d, %Y")

print("Formatted date: ", formatted_date)

これにより、「年月日」の形式で日付が出力されます。

Python Datetime: 例を含む包括的なガイド

  • strptime()

このメソッドを使用すると、日付を表す文字列を Date オブジェクトに解析できます。以下は、文字列日付を Date オブジェクトに変換する例です。

import datetime

# String representing a date
date_string = "May 22, 2023"

# Parse the string into a date object
parsed_date = datetime.datetime.strptime(date_string, "%B %d, %Y").date()

print("Parsed date: ", parsed_date)

これにより、日付文字列から作成された日付オブジェクトが出力されます。

Python Datetime: 例を含む包括的なガイド

時間クラスの使用方法

The Time class allows you to work with time instances (hour, minute, second, microsecond). With the time class, you can create a custom time object with datetime.time().

The following example demonstrates creating a custom time object:

import datetime

# Create a custom time object
custom_time = datetime.time(17, 40)

print("Custom time: ", custom_time)

In the datetime.time() function, you provide the hour and minute as arguments.

This script will output 17:40:00, as specified in the Python code.

Python Datetime: 例を含む包括的なガイド

The Time class provides useful methods, such as:

  • strftime()

This method allows you to format the time object as a string. Below is an example of this function:

import datetime

# Create a custom time object
custom_time = datetime.time(17, 40)

# Format the time object as a string
formatted_time = custom_time.strftime("%H:%M")

print("Formatted time: ", formatted_time)

This will output the local time formatted as “Hour:Minute”.

Python Datetime: 例を含む包括的なガイド

  • strptime()

This function allows you to parse a string representing time into a Time object. The following example demonstrates this function:

from datetime import time

# String representing a time
time_string = "17:40"

# Parse the string into a time object
parsed_time = datetime.datetime.strptime(time_string, "%H:%M").time()

print("Parsed time: ", parsed_time)

This will output the time objects created from the time string.

Python Datetime: 例を含む包括的なガイド

How to Use The Timedelta Class

The Timedelta class allows you to represent represents a duration or difference between two dates or times.

With Timedelta class, you can perform the following operations:

  • Calculate the difference between two dates or times

An example of calculating the difference between two dates is given below:

 import datetime

# Create two custom date objects
date1 = datetime.date(2023, 5, 22)
date2 = datetime.date(2023, 6, 1)

# Calculate the difference between the two dates
date_difference = date2 - date1

print("Difference between the dates is: ", date_difference.days, "days")

In this example, date_difference is a timedelta object representing the difference between date2 and date1. The .days property gives the number of days between the two dates.

Python Datetime: 例を含む包括的なガイド

  • Add or subtract a duration to a date or time

An example of adding a duration to a date is given below:

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Create a duration of 10 days
duration = datetime.timedelta(days=10)

# Add the duration to the date
new_date = custom_date + duration

print("New date: ", new_date)

In this example, duration is a timedelta object representing a duration of 10 days. We use the + operator to add this duration to custom_date.

Python Datetime: 例を含む包括的なガイド

How to Use the Timezone Class

The Timezone class allows you to handle time zones and daylight saving time adjustments.

You can perform the following operation with timezone class:

  • Create a timezone object

To create a timezone object, you can use the datetime.timezone() function. The following example demonstrates creating a timezone object:

import datetime

# Create a timezone object for a timezone 2 hours ahead of UTC
two_hours_ahead = datetime.timezone(datetime.timedelta(hours=2))

print("Timezone object: ", two_hours_ahead)

In this example, two_hours_ahead is a timezone object representing a timezone that is 2 hours ahead of Coordinated Universal Time (UTC).

This script will output a timezone object like .

Python Datetime: 例を含む包括的なガイド

  • Object with a specific timezone

To achieve this, you can use the .replace(tzinfo=tz) function. The following example demonstrates this function:

import datetime

# Create a naive datetime object
naive_datetime = datetime.datetime(2023, 5, 22, 17, 40)

# Create a timezone object for a timezone 2 hours ahead of UTC
two_hours_ahead = datetime.timezone(datetime.timedelta(hours=2))

# Convert the naive datetime object to an aware object
aware_datetime = naive_datetime.replace(tzinfo=two_hours_ahead)

print("Aware datetime object: ", aware_datetime)

In this example, naive_datetime is a datetime object that does not have any timezone information. The two_hours_ahead variable is a timezone object representing a timezone that is 2 hours ahead of UTC.

The replace(tzinfo=two_hours_ahead) method is used to create a new datetime object with the same date and time as naive_datetime, but with tzinfo set to two_hours_ahead.

Python Datetime: 例を含む包括的なガイド

The Timezone helps you maintain accurate and consistent time values when working with data that spans multiple time zones.

You have gone through some of the most important functions in the datetime module in Python. In the next section we will implement some of the above functions to a case studywhich will give you a practical look into the implementation of these datetime module in your projects.

Implementing the DateTime Module Functions to a Case Study

Let’s consider a case study where we are given a dataset of different events that happened around the world. The dataset has corresponding dates and times in a string format.

私たちのタスクは、これらの日付と時刻を DateTime オブジェクトに変換し、必要に応じて操作を実行することです。

次のデータセットが与えられたとします。

Python Datetime: 例を含む包括的なガイド

変数のデータ型を確認すると、日付と時刻が文字列として格納されていることがわかります。したがって、分析を実行する前に、日付と時刻の列を適切な形式に変換する必要があります。

これを行うには、次のコードを使用できます。

import datetime

# Convert 'Date' and 'Time' strings into datetime objects
df['DateTime'] = df['Date'] + ' ' + df['Time']
df['DateTime'] = df['DateTime'].apply(lambda x: datetime.datetime.strptime(x, "%b %d, %Y %H:%M"))

print(df)

このコード ブロックでは、まず、「Date」列と「Time」列を連結して、DataFrame に新しい列「DateTime」を作成します。次に、この新しい列の各値に datetime.strptime 関数を適用して、日付と時刻の文字列を datetime オブジェクトに変換します。最後に、DataFrame を出力して結果を確認します。

Python Datetime: 例を含む包括的なガイド

次にやりたいことは、2 つのイベントの差を計算することです。これを行うには、次のコードを使用できます。

duration = df.loc[1, 'DateTime'] - df.loc[0, 'DateTime']
print("Duration between Event1 and Event2: ", duration)

この Python スクリプトは、「Event1」と「Event2」の間の継続時間を計算します。

Python Datetime: 例を含む包括的なガイド

最後に、datetime オブジェクトを別のタイムゾーンに変換しましょう。datetime モジュールの Timezone 関数を使用してこれを実現できる場合。

# Create a timezone object for UTC
utc_tz = datetime.timezone(datetime.timedelta(0))

# Convert the datetime objects into UTC
df['DateTime_UTC'] = df['DateTime'].apply(lambda x: x.replace(tzinfo=utc_tz))

print(df)

このコードでは、UTC のタイムゾーン オブジェクトを作成します。次に、ラムダ関数を「DateTime」列に適用して、DataFrame に「DateTime_UTC」という名前の新しい列を作成します。これにより、各日時オブジェクトのタイムゾーン情報が UTC に置き換えられます。

Python Datetime: 例を含む包括的なガイド

上記のケーススタディの例を通じて、DateTime モジュールが提供するさまざまな関数がどのように連携して日付と時刻を適切な形式に操作するかがわかります。

datetime モジュールの関数のいくつかについては理解できたので、次に、より複雑なプロジェクトに取り組むときに使用するいくつかの追加関数を見てみましょう。

上記の関数以外にも、問題に応じて使用できる便利な関数が多数あります。Python 開発者は、ニーズを満たす関数を探すためにドキュメントページを開いたままにすることがよくあります。あなたも同じようにすることをお勧めします。

追加の日付と時刻の関数

このセクションでは、Python datetimeモジュールの追加関数について説明します。これには、 ctime()関数とともに、曜日、月、曜日の名前の取得が含まれます。

日付から平日を取得する方法

datetimeモジュールには、曜日を整数 (月曜日は 0、日曜日は 6) として返すWeekday()関数付属しています。

この関数を使用するには、日付または日時オブジェクトでこの関数を呼び出すことができます。

import datetime

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

print(weekday_number)

上記のコードの出力を以下の画像に示します。

Python Datetime: 例を含む包括的なガイド

現在の現地の日付は 2023 年 5 月 23 日で、平日は月曜日です。

日付から月と曜日の名前を取得する方法

datetime を使用すると、月と曜日の名前を取得することもできます。

日付または日時オブジェクトを文字列としてフォーマットするstrftime()関数を使用できます。

以下は、 strftime()関数を使用して月と曜日の名前を取得する方法の例です。

import datetime

today = datetime.date.today()
weekday_name = today.strftime('%A')
month_name = today.strftime('%B')

print(weekday_name)
print(month_name)

このコードは、出力に曜日名と月名を出力します。

Python Datetime: 例を含む包括的なガイド

Ctime関数の使用方法

datetimeモジュールのctime ()関数は、「Day Mon DD HH:MM:SS YYYY」の形式で、日付または日時オブジェクトの文字列表現を返します。

ctimeは、スタンドアロン関数ではなく、datetimeオブジェクトのメソッドです。

以下は、コード内で ctime 関数を使用する例です。

import datetime

now = datetime.datetime.now()
formatted_date = now.ctime()

print(formatted_date)

上記のコードは、日付オブジェクトの文字列表現を返します。

Python Datetime: 例を含む包括的なガイド

時系列データの操作の詳細については、次のビデオをご覧ください。

最終的な考え

Python プログラマーとして、datetime モジュールを習得することは重要です。これは、日付、時刻、時間間隔を処理できるツールキットです。これらは、現実世界のデータで頻繁に遭遇する要素です。

このモジュールは、文字列を日時オブジェクトに変換し、タイムゾーン変換を処理し、日付と時刻の操作を実行するために必要です。

datetime モジュールの使用方法を学ぶことで、独自のプロジェクトでこれらのタスクを処理する準備が整います。


Python における Self とは: 実際の例

Python における Self とは: 実際の例

Python における Self とは: 実際の例

RでRDSファイルを保存してロードする方法

RでRDSファイルを保存してロードする方法

R の .rds ファイルからオブジェクトを保存および読み込む方法を学習します。このブログでは、R から LuckyTemplates にオブジェクトをインポートする方法についても説明します。

最初の N 営業日の再考 – DAX コーディング言語ソリューション

最初の N 営業日の再考 – DAX コーディング言語ソリューション

この DAX コーディング言語チュートリアルでは、GENERATE 関数の使用方法とメジャー タイトルを動的に変更する方法を学びます。

LuckyTemplates のマルチスレッド動的ビジュアル手法を使用したインサイトのショーケース

LuckyTemplates のマルチスレッド動的ビジュアル手法を使用したインサイトのショーケース

このチュートリアルでは、マルチスレッド動的ビジュアル手法を使用して、レポート内の動的データ視覚化から洞察を作成する方法について説明します。

LuckyTemplates のフィルター コンテキストの概要

LuckyTemplates のフィルター コンテキストの概要

この記事では、フィルター コンテキストについて説明します。フィルター コンテキストは、LuckyTemplates ユーザーが最初に学習する必要がある主要なトピックの 1 つです。

LuckyTemplates Online Service でアプリを使用する際の最良のヒント

LuckyTemplates Online Service でアプリを使用する際の最良のヒント

LuckyTemplates Apps オンライン サービスが、さまざまなソースから生成されたさまざまなレポートや分析情報の管理にどのように役立つかを示したいと思います。

時間の経過に伴う利益率の変化を分析する – LuckyTemplates と DAX を使用した分析

時間の経過に伴う利益率の変化を分析する – LuckyTemplates と DAX を使用した分析

LuckyTemplates でのメジャー分岐や DAX 数式の結合などの手法を使用して、利益率の変化を計算する方法を学びます。

DAX Studio でのデータ キャッシュのマテリアライゼーションのアイデア

DAX Studio でのデータ キャッシュのマテリアライゼーションのアイデア

このチュートリアルでは、データ キャッシュの具体化のアイデアと、それが結果を提供する際の DAX のパフォーマンスにどのように影響するかについて説明します。

LuckyTemplates を使用したビジネス レポート

LuckyTemplates を使用したビジネス レポート

これまで Excel を使用している場合は、ビジネス レポートのニーズに合わせて LuckyTemplates の使用を開始するのに最適な時期です。

LuckyTemplates ゲートウェイとは何ですか? 知っておくべきことすべて

LuckyTemplates ゲートウェイとは何ですか? 知っておくべきことすべて

LuckyTemplates ゲートウェイとは何ですか? 知っておくべきことすべて