Pythonで日時を日付に変換する方法
この記事では、Python で DateTime を日付に変換する方法を見ていきます。このために、strptime() メソッドと Pandas モジュールを使用します。このメソッドは、文字列から DateTime オブジェクトを作成するために使用されます。次に、次を使用して DateTime オブジェクトから日付を抽出します。 date() 関数 そして パンダからの dt.date Python で。
方法 1: DateTime を使用して Python で DateTime を日付に変換する
日付と時刻を操作するためのクラスは、 Python 日時 モジュール。これらのクラスによって、日付、時刻、および時間間隔を処理するための多数の機能が提供されます。 Python は date と DateTime をオブジェクトとして扱うため、これらを操作するときは、実際には文字列やタイムスタンプではなくオブジェクトを操作していることになります。
strptime() の構文
パラメーター:
arg: データ型形式として datetime に変換する整数、float、タプル、Series、Dataframe を指定できます。これは str になりますが、デフォルトは None です。解析時間の strftime (例: %d/%m/%Y)。%f はナノ秒まで解析することに注意してください。
例 1: DateTime を日付に変換する
この例では、datetime_str を作成しました。 2001年8月24日101010 、その形式は %d%b%Y%H%M%S。
Python3
# import important module> import> datetime> from> datetime> import> datetime> # Create datetime string> datetime_str> => '24AUG2001101010'> print> (> 'datetime string : {}'> .> format> (datetime_str))> # call datetime.strptime to convert> # it into datetime datatype> datetime_obj> => datetime.strptime(datetime_str,> > '%d%b%Y%H%M%S'> )> # It will print the datetime object> print> (datetime_obj)> # extract the time from datetime_obj> date> => datetime_obj.date()> print> (date)> |
出力:
datetime string : 24AUG2001101010 2001-08-24 10:10:10 2001-08-24
例 2: DateTime を数値日付に変換します。
この例では、datetime_str を作成しました。 100201095407 、その形式は %d%m%y%H%M%S 。
Python3
# import important module> import> datetime> from> datetime> import> datetime> # Create datetime string> datetime_str> => '100201095407'> print> (> 'datetime string : {}'> .> format> (datetime_str))> # call datetime.strptime to convert> # it into datetime datatype> datetime_obj> => datetime.strptime(datetime_str,> > '%d%m%y%H%M%S'> )> # It will print the datetime object> print> (datetime_obj)> # extract the time from datetime_obj> date> => datetime_obj.date()> # it will print date that we have> # extracted from datetime obj> print> (date)> |
出力 :
datetime string : 100201095407 2001-02-10 09:54:07 2001-02-10
例 3: DateTime を現在の日付に変換します。
この例では、現在の日時を取得し、その日付をオブジェクトから抽出します。
Python3
# import important module> from> datetime> import> datetime> # call datetime.strptime to> # convert it into datetime datatype> datetime_obj> => datetime.now()> # It will print the datetime object> print> (datetime_obj)> # extract the time from datetime_obj> date> => datetime_obj.date()> print> (date)> |
出力:
2021-08-07 06:30:20.227879 2021-08-07
方法 2: Pandas を使用して Python で DateTime を日付に変換する
Pandas は、日時データに対して必要なすべてのタスクを実行できる別のツール セットを提供します。以下で説明する例を使って理解してみましょう。
例:
日付値と DateTime 値は両方とも、print コマンドを使用して出力に表示されます。 DateTime 値は、最初に Pandas DataFrame の列に追加されます。次に、DateTime 値は、dt.date() 関数を使用して日付値に変換されます。
Python3
import> pandas as pd> df> => pd.DataFrame({> 'time'> : [> '2022-7-16 11:05:00'> ,> > '2025-7-18 12:00:30'> ]})> print> (df)> df[> 'time'> ]> => pd.to_datetime(df[> 'time'> ]).dt.date> print> (df)> |
出力:
time 0 2022-7-16 11:05:00 1 2025-7-18 12:00:30 time 0 2022-07-16 1 2025-07-18