Python では、日付と時刻はそれ自体のデータ型ではなく、という名前のモジュールです。 日付時刻 Python では、日付と時刻を操作するためにインポートできます。 Python 日時モジュール Python に組み込まれているため、外部からインストールする必要はありません。
この記事では、その方法について説明します。 Python の日時 Python の DateTime モジュールの主要なクラスとは何ですか。
目次
- Python 日時モジュール
- Python 日付クラス
- Python 時間クラス
- Python 日時クラス
- Python タイムデルタ クラス
- Python DateTime.tzinfo()
- Python の DateTime タイムゾーン
Python 日時モジュール
Python 日時 モジュールは、日付と時刻を扱うクラスを提供します。これらのクラスは、日付、時刻、および時間間隔を処理するためのいくつかの関数を提供します。 Date と DateTime は Python のオブジェクトであるため、これらを操作するときは、文字列やタイムスタンプではなくオブジェクトを操作することになります。
DateTime モジュールは 6 つの主要なクラスに分類されます。
- 日付 – 現在のグレゴリオ暦が常に有効であり、今後も有効であると仮定した、理想化された素朴な日付。その属性は年、月、日です。参照できます – Python DateTime – 日付クラス
- 時間 – 毎日がちょうど 24*60*60 秒であると仮定した、特定の日に依存しない理想的な時間。その属性は、時、分、秒、マイクロ秒、tzinfo です。参照できます – Python DateTime – 時間クラス
- 日付時刻 – これは、日付と時刻と、年、月、日、時、分、秒、マイクロ秒、tzinfo の属性の組み合わせです。参照できます – Python DateTime – DateTime クラス
- タイムデルタ – 2 つの日付、時刻、または日時インスタンスの差をマイクロ秒単位の解像度で表す期間。参照できます – Python DateTime – Timedelta クラス
- ツインフォ – タイムゾーン情報オブジェクトを提供します。参照できます – Python – datetime.tzinfo()
- タイムゾーン – UTC からの固定オフセットとして tzinfo 抽象基本クラスを実装するクラス (バージョン 3.2 の新機能)。参照できます – Python でのタイムゾーンの処理
Python 日付クラス
date クラスは、Python で日付オブジェクトをインスタンス化するために使用されます。このクラスのオブジェクトがインスタンス化されると、次の形式で日付を表します。 YYYY-MM-DD 。このクラスのコンストラクターには、年、月、および日付の 3 つの必須引数が必要です。
Python の日付クラスの構文
class datetime.date(year, month, day)>
引数は次の範囲内である必要があります –
- MIYEAR <= 年 <= MAXYEAR
- 1 <= 月 <= 12
- 1 <= 日 <= 指定された月および年の日数
注記 – 引数が整数でない場合は TypeError が発生し、範囲外の場合は ValueError が発生します。
Python でデータを表す日付オブジェクト
コンストラクターを初期化し、年、月、日の形式で引数を渡します。
Python3
# Python program to> # demonstrate date class> # import the date class> from> datetime>import> date> my_date>=> date(>1996>,>12>,>11>)> print>(>'Date passed as argument is'>, my_date)> # Uncommenting my_date = date(1996, 12, 39)> # will raise an ValueError as it is> # outside range> # uncommenting my_date = date('1996', 12, 11)> # will raise a TypeError as a string is> # passed instead of integer> |
>
世界で一番素敵な笑顔
>
出力:
Date passed as argument is 1996-12-11>
Traceback (most recent call last): File '/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py', line 14, in my_date = date(1996, 12, 39) ValueError: day is out of range for month Traceback (most recent call last): File '/home/53b974e10651f1853eee3c004b48c481.py', line 18, in my_date = date('1996', 12, 11) TypeError: an integer is required (got type str)> 現在の日付を取得する
現在のローカル日付を返すには、date クラスの today() 関数が使用されます。 today() 関数には、いくつかの属性 (年、月、日) が付属しています。これらは個別に印刷できます。
Python3
# Python program to> # print current date> from> datetime>import> date> # calling the today> # function of date class> today>=> date.today()> print>(>'Today's date is'>, today)> |
>
>出力
Today's date is 2021-08-19>
今日の年、月、日付を取得する
date クラスの年、月、および日付属性を使用して、日付オブジェクトから年、月、および日付の属性を取得できます。
Python3
from> datetime>import> date> # date object of today's date> today>=> date.today()> print>(>'Current year:'>, today.year)> print>(>'Current month:'>, today.month)> print>(>'Current day:'>, today.day)> |
>
>出力
Current year: 2021 Current month: 8 Current day: 19>
タイムスタンプから日付を取得する
fromtimestamp() メソッドを使用して、タイムスタンプ y= から日付オブジェクトを作成できます。タイムスタンプは、UTC の 1970 年 1 月 1 日から特定の日付までの秒数です。
Python3
from> datetime>import> datetime> # Getting Datetime from timestamp> date_time>=> datetime.fromtimestamp(>1887639468>)> print>(>'Datetime from timestamp:'>, date_time)> |
>
>出力
Datetime from timestamp: 2029-10-25 16:17:48>
日付を文字列に変換
isoformat() と strftime() の 2 つの関数を使用して、日付オブジェクトを文字列表現に変換できます。
Python3
from> datetime>import> date> > # calling the today> # function of date class> today>=> date.today()> > # Converting the date to the string> Str> => date.isoformat(today)> print>(>'String Representation'>,>Str>)> print>(>type>(>Str>))> |
>
>出力
String Representation 2021-08-19>
Date クラスのメソッドのリスト
| 関数名 | 説明 |
|---|---|
| ctime() | 日付を表す文字列を返します |
| fromisocalendar() | ISO カレンダーに対応する日付を返します。 |
| fromisoformat() | 日付の文字列表現から日付オブジェクトを返します。 |
| fromordinal() | 予兆グレゴリオ序数から日付オブジェクトを返します。1 年目の 1 月 1 日は序数 1 です。 |
| fromtimestamp() | POSIXタイムスタンプから日付オブジェクトを返します。 |
| isocalendar() | タプルの年、週、曜日を返します。 |
| isoformat() | 日付の文字列表現を返します。 |
| isoweekday() | 月曜日が 1、日曜日が 7 である整数として曜日を返します。 |
| 交換する() | 指定されたパラメータを使用して日付オブジェクトの値を変更します |
| strftime() | 指定された形式で日付の文字列表現を返します。 |
| タイムタプル() | time.struct_time 型のオブジェクトを返します。 |
| 今日() | 現在のローカル日付を返します |
| 序数() | 日付の予兆グレゴリオ序数を返します。1 年目の 1 月 1 日の序数は 1 です。 |
| 平日() | 月曜日が 0、日曜日が 6 である整数として曜日を返します。 |
Python 時間クラス
time クラスは、曜日に関係なく、現地時間を表す time オブジェクトを作成します。
コンストラクターの構文:
class datetime.time(時=0、分=0、秒=0、マイクロ秒=0、tzinfo=なし、*、fold=0)
すべての引数はオプションです。 tzinfo は None にすることができます。それ以外の場合、すべての属性は次の範囲の整数である必要があります。
- 0 <= 時間 < 24
- 0 <= 分 < 60
- 0 <= 秒 < 60
- 0 <= マイクロ秒 < 1000000
- [0, 1] で折り畳む
例 1: Python で時間を表す Time オブジェクト
Python3
二分木の種類
# Python program to> # demonstrate time class> from> datetime>import> time> # calling the constructor> my_time>=> time(>13>,>24>,>56>)> print>(>'Entered time'>, my_time)> # calling constructor with 1> # argument> my_time>=> time(minute>=>12>)> print>(>'
Time with one argument'>, my_time)> # Calling constructor with> # 0 argument> my_time>=> time()> print>(>'
Time without argument'>, my_time)> # Uncommenting time(hour = 26)> # will rase an ValueError as> # it is out of range> # uncommenting time(hour ='23')> # will raise TypeError as> # string is passed instead of int> |
>
>
出力:
Entered time 13:24:56 Time with one argument 00:12:00 Time without argument 00:00:00>
Traceback (most recent call last): File '/home/95ff83138a1b3e67731e57ec6dddef25.py', line 21, in print(time(hour=26)) ValueError: hour must be in 0..23 Traceback (most recent call last): File '/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py', line 21, in print(time(hour='23')) TypeError: an integer is required (got type str)>
例 2: 時、分、秒、マイクロ秒を取得する
時間オブジェクトを作成した後、その属性を個別に出力することもできます。
Python3
from> datetime>import> time> Time>=> time(>11>,>34>,>56>)> print>(>'hour ='>, Time.hour)> print>(>'minute ='>, Time.minute)> print>(>'second ='>, Time.second)> print>(>'microsecond ='>, Time.microsecond)> |
>
>
出力:
hour = 11 minute = 34 second = 56 microsecond = 0>
例 3: 時刻オブジェクトを文字列に変換する
isoformat() メソッドを使用して、時刻オブジェクトを文字列に変換できます。
Python3
from> datetime>import> time> # Creating Time object> Time>=> time(>12>,>24>,>36>,>1212>)> # Converting Time object to string> Str> => Time.isoformat()> print>(>'String Representation:'>,>Str>)> print>(>type>(>Str>))> |
>
>出力
String Representation: 12:24:36.001212>
Time クラスのメソッドのリスト
| 関数名 | 説明 |
|---|---|
| dst() | tzinfo.dst() は tzinfo が None ではない場合を返します。 |
| fromisoformat() | 時刻の文字列表現から時刻オブジェクトを返します。 |
| isoformat() | 時刻オブジェクトから時刻の文字列表現を返します。 |
| 交換する() | 指定されたパラメータを使用して時間オブジェクトの値を変更します |
| strftime() | 指定された形式で時刻の文字列表現を返します。 |
| tzname() | tzinfo.tzname() は tzinfo ではありませんが None を返します |
| utcoffset() | tzinfo.utcffsets() を返します。tzinfo は None ではありません。 |
Python 日時クラス
の DateTime クラス 日付と時刻の両方の情報が含まれます。 date オブジェクトと同様に、datetime は現在のグレゴリオ暦が両方向に拡張されていることを前提としています。 time オブジェクトと同様に、datetime は毎日が正確に 3600*24 秒であることを前提としています。
コンストラクターの構文:
class datetime.datetime(年、月、日、時=0、分=0、秒=0、マイクロ秒=0、tzinfo=なし、*、fold=0)
年、月、日の引数は必須です。 tzinfo は None にすることができます。それ以外のすべての属性は次の範囲の整数でなければなりません –
- MIYEAR <= 年 <= MAXYEAR
- 1 <= 月 <= 12
- 1 <= 日 <= 指定された月および年の日数
- 0 <= 時間 < 24
- 0 <= 分 < 60
- 0 <= 秒 < 60
- 0 <= マイクロ秒 < 1000000
- [0, 1] で折り畳む
注記 – 整数以外の引数を渡すと TypeError が発生し、範囲外の引数を渡すと ValueError が発生します。
Python で DateTime を表す DateTime オブジェクト
Python3
# Python program to> # demonstrate datetime object> from> datetime>import> datetime> # Initializing constructor> a>=> datetime(>1999>,>12>,>12>)> print>(a)> # Initializing constructor> # with time parameters as well> a>=> datetime(>1999>,>12>,>12>,>12>,>12>,>12>,>342380>)> print>(a)> |
C言語のr
>
>
出力:
1999-12-12 00:00:00 1999-12-12 12:12:12.342380>
年、月、時、分、タイムスタンプを取得する
DateTime オブジェクトを作成した後、その属性を個別に出力することもできます。
Python3
from> datetime>import> datetime> a>=> datetime(>1999>,>12>,>12>,>12>,>12>,>12>)> print>(>'year ='>, a.year)> print>(>'month ='>, a.month)> print>(>'hour ='>, a.hour)> print>(>'minute ='>, a.minute)> print>(>'timestamp ='>, a.timestamp())> |
>
>
出力:
year = 1999 month = 12 hour = 12 minute = 12 timestamp = 945000732.0>
現在の日付と時刻
Datetime.now() 関数を使用して、現在の日付と時刻を出力できます。 now() 関数は、現在のローカル日付と時刻を返します。
Python3
from> datetime>import> datetime> # Calling now() function> today>=> datetime.now()> print>(>'Current date and time is'>, today)> |
>
>
出力:
Current date and time is 2019-10-25 11:12:11.289834>
Python の日時を文字列に変換する
Python では、次を使用して Datetime を文字列に変換できます。 日時.strftime および datetime.isoformat メソッド。
Python3
from> datetime>import> datetime as dt> # Getting current date and time> now>=> dt.now()> string>=> dt.isoformat(now)> print>(string)> print>(>type>(string))> |
>
>出力
2021-08-19T18:13:25.346259>
Datetime クラス メソッドのリスト
| 関数名 | 説明 |
|---|---|
| astimezone() | タイムゾーン情報を含む DateTime オブジェクトを返します。 |
| 組み合わせる() | 日付と時刻のオブジェクトを結合して、DateTime オブジェクトを返します。 |
| ctime() | 日付と時刻の文字列表現を返します。 |
| 日付() | Date クラス オブジェクトを返します。 |
| fromisoformat() | 日付と時刻の文字列表現から日時オブジェクトを返します。 |
| fromordinal() | 予兆グレゴリオ序数から日付オブジェクトを返します。1 年目の 1 月 1 日が序数 1 になります。時、分、秒、マイクロ秒は 0 です。 |
| fromtimestamp() | POSIX タイムスタンプから日付と時刻を返す |
| isocalendar() | タプルの年、週、曜日を返します。 |
| isoformat() | 日付と時刻の文字列表現を返します。 |
| isoweekday() | 月曜日が 1、日曜日が 7 である整数として曜日を返します。 |
| 今() | tz パラメータを使用して現在のローカル日付と時刻を返します。 |
| 交換する() | DateTime オブジェクトの特定の属性を変更します。 |
| strftime() | 指定された形式の DateTime オブジェクトの文字列表現を返します。 |
| strptime() | 日付文字列に対応する DateTime オブジェクトを返します。 |
| 時間() | Time クラス オブジェクトを返します。 |
| タイムタプル() | time.struct_time 型のオブジェクトを返します。 |
| タイムッツ() | Time クラス オブジェクトを返します。 |
| 今日() | tzinfo を None としてローカルの DateTime を返します |
| 序数() | 日付の予兆グレゴリオ序数を返します。1 年目の 1 月 1 日の序数は 1 です。 |
| tzname() | タイムゾーンの名前を返します |
| utcfromtimestamp() | POSIX タイムスタンプから UTC を返す |
| utcoffset() | UTC オフセットを返します |
| utcnow() | 現在の UTC 日付と時刻を返します |
| 平日() | 月曜日が 0、日曜日が 6 である整数として曜日を返します。 |
Python タイムデルタ クラス
Python の timedelta クラスは、日付の差を計算するために使用され、Python での日付操作にも使用できます。これは、日付操作を実行する最も簡単な方法の 1 つです。
コンストラクターの構文:
class datetime.timedelta(日=0、秒=0、マイクロ秒=0、ミリ秒=0、分=0、時間=0、週=0)
戻り値: 日付
DateTime オブジェクトに日を追加する
timedelta 関数のデモンストレーション
Python3
123moviesに似た映画ウェブサイト
from> datetime>import> datetime, timedelta> # Using current time> ini_time_for_now>=> datetime.now()> # printing initial_date> print>(>'initial_date'>,>str>(ini_time_for_now))> # Calculating future dates> # for two years> future_date_after_2yrs>=> ini_time_for_now>+> timedelta(days>=>730>)> future_date_after_2days>=> ini_time_for_now>+> timedelta(days>=>2>)> # printing calculated future_dates> print>(>'future_date_after_2yrs:'>,>str>(future_date_after_2yrs))> print>(>'future_date_after_2days:'>,>str>(future_date_after_2days))> |
>
>
出力:
initial_date 2019-10-25 12:01:01.227848 future_date_after_2yrs: 2021-10-24 12:01:01.227848 future_date_after_2days: 2019-10-27 12:01:01.227848>
2 つの日付と時刻の違い
このクラスを使用して、日付と時刻の違いを見つけることもできます。
Python3
# Timedelta function demonstration> from> datetime>import> datetime, timedelta> # Using current time> ini_time_for_now>=> datetime.now()> # printing initial_date> print>(>'initial_date'>,>str>(ini_time_for_now))> # Some another datetime> new_final_time>=> ini_time_for_now>+> > >timedelta(days>=>2>)> # printing new final_date> print>(>'new_final_time'>,>str>(new_final_time))> # printing calculated past_dates> print>(>'Time difference:'>,>str>(new_final_time>-> >ini_time_for_now))> |
>
>
出力:
initial_date 2019-10-25 12:02:32.799814 new_final_time 2019-10-27 12:02:32.799814 Time difference: 2 days, 0:00:00>
Timedelta クラスでサポートされる操作
| オペレーター | 説明 |
|---|---|
| 加算(+) | 2 つの timedelta オブジェクトを追加して返します。 |
| 減算(-) | 2 つの timedelta オブジェクトを減算して返します。 |
| 乗算(*) | timedelta オブジェクトを float または int で乗算します。 |
| 分割 (/) | timedelta オブジェクトを float または int で除算します。 |
| フロア区分(//) | timedelta オブジェクトを float または int で除算し、出力のフロア値の int を返します。 |
| モジュール (%) | 2 つの timedelta オブジェクトを除算し、剰余を返します。 |
| +(タイムデルタ) | 同じ timedelta オブジェクトを返します |
| -(タイムデルタ) | -1*timedelta の結果を返します |
| abs(タイムデルタ) | timedelta.days> 1=0 の場合は +(timedelta) を返し、それ以外の場合は -(timedelta) を返します。 |
| str(タイムデルタ) | (+/-) day[s]、HH:MM:SS.UUUUUU の形式の文字列を返します。 |
| repr(タイムデルタ) | コンストラクター呼び出しの形式で文字列表現を返します。 |
Python で DateTime をフォーマットする
日付表現は場所によって異なる可能性があるため、DateTime の書式設定が非常に必要になる場合があります。国によっては yyyy-mm-dd である場合もあれば、dd-mm-yyyy である場合もあります。 Python Datetime をフォーマットするには、strptime 関数と strftime 関数を使用できます。
Python 日時 strftime
strftime() メソッドは、指定された日付、時刻、または DateTime オブジェクトを指定された形式の文字列表現に変換します。
Python 日時形式
strftime() 関数をデモする Python プログラム
Python3
from> datetime>import> datetime as dt> # Getting current date and time> now>=> dt.now()> print>(>'Without formatting'>, now)> # Example 1> s>=> now.strftime(>'%A %m %-Y'>)> print>(>'
Example 1:'>, s)> # Example 2> s>=> now.strftime(>'%a %-m %y'>)> print>(>'
Example 2:'>, s)> # Example 3> s>=> now.strftime(>'%-I %p %S'>)> print>(>'
Example 3:'>, s)> # Example 4> s>=> now.strftime(>'%H:%M:%S'>)> print>(>'
Example 4:'>, s)> |
>
>出力
Without formatting 2021-08-19 18:16:25.881661 Example 1: Thursday 08 2021 Example 2: Thu 8 21 Example 3: 6 PM 25 Example 4: 18:16:25>
注記: 詳細については、以下を参照してください。 strftime() メソッド 。
Python の日時 strptime
strptime() は、指定された文字列から DateTime オブジェクトを作成します。
例: 日時 strptime
Python3
# import datetime module from datetime> from> datetime>import> datetime> > # consider the time stamps from a list in string> # format DD/MM/YY H:M:S.micros> time_data>=> [>'25/05/99 02:35:8.023'>,>'26/05/99 12:45:0.003'>,> >'27/05/99 07:35:5.523'>,>'28/05/99 05:15:55.523'>]> > # format the string in the given format : day/month/year> # hours/minutes/seconds-micro seconds> format_data>=> '%d/%m/%y %H:%M:%S.%f'> > # Using strptime with datetime we will format string> # into datetime> for> i>in> time_data:> >print>(datetime.strptime(i, format_data))> |
>
>出力
1999-05-25 02:35:08.023000 1999-05-26 12:45:00.003000 1999-05-27 07:35:05.523000 1999-05-28 05:15:55.523000>
Python DateTime.tzinfo()
の datetime.now() 関数 タイムゾーンに関する情報は含まれていません。現在のシステム時間のみが使用されます。 Tzinfo は、Python の抽象基本クラスです。直接インスタンス化することはできません。具象サブクラスは、この抽象クラスから派生し、それが提供するメソッドを実装する必要があります。
Python DateTime.tzinfo() オブジェクトのリスト
| 関数名 | 説明 |
|---|---|
| dst() | tzinfo.dst() は tzinfo が None ではない場合を返します。 |
| fromutc() | この関数の目的は日時データを調整することです。 自分自身の現地時間で同等の DateTime を返します。 |
| tzname() | tzinfo.tzname() は tzinfo ではありませんが None を返します |
| utcoffset() | tzinfo.utcffsets() を返します。tzinfo は None ではありません。 |
例
tzinfo クラスのインスタンスは、DateTime オブジェクト コンストラクターと時刻オブジェクト コンストラクターに提供できます。これは、現地時間を UTC に変換したり、夏時間を考慮したりするなどのシナリオで使用されます。
Python3
import> datetime as dt> from> dateutil>import> tz> tz_string>=> dt.datetime.now(dt.timezone.utc).astimezone().tzname()> print>(>'datetime.now() :'>, tz_string)> NYC>=> tz.gettz(>'Europe / Berlin'>)> dt1>=> dt.datetime(>2022>,>5>,>21>,>12>,>0>)> dt2>=> dt.datetime(>2022>,>12>,>21>,>12>,>0>, tzinfo>=>NYC)> print>(>'Naive Object :'>, dt1.tzname())> print>(>'Aware Object :'>, dt2.tzname())> |
アメリカには都市がいくつありますか
>
>
出力:
datetime.now() : IST Naive Object : None Aware Object : None>
Python の DateTime タイムゾーン
DateTime のタイムゾーンは、特定の地域のタイムゾーンに従って時間を表示したい場合に使用できます。これは、 pytzモジュール パイソンの。このモジュールは日付と時刻の変換機能を提供し、ユーザーが国際的なクライアント ベースにサービスを提供するのに役立ちます。
Python3
from> datetime>import> datetime> from> pytz>import> timezone> format> => '%Y-%m-%d %H:%M:%S %Z%z'> # Current time in UTC> now_utc>=> datetime.now(timezone(>'UTC'>))> print>(now_utc.strftime(>format>))> timezones>=> [>'Asia/Kolkata'>,>'Europe/Kiev'>,>'America/New_York'>]> for> tzone>in> timezones:> ># Convert to Asia/Kolkata time zone> >now_asia>=> now_utc.astimezone(timezone(tzone))> >print>(now_asia.strftime(>format>))> |
>
>出力
2021-08-19 18:27:28 UTC+0000 2021-08-19 23:57:28 IST+0530 2021-08-19 21:27:28 EEST+0300 2021-08-19 14:27:28 EDT-0400>