Python日時
Pythonの日付
Pythonの日付はそれ自体のデータ型ではありませんが、datetime
日付オブジェクトとして日付を処理するように名前が付けられたモジュールをインポートできます。
例
日時モジュールをインポートし、現在の日付を表示します。
import datetime
x = datetime.datetime.now()
print(x)
日付出力
上記の例のコードを実行すると、結果は次のようになります。
2022-01-29 15:57:36.325761
日付には、年、月、日、時、分、秒、およびマイクロ秒が含まれます。
このdatetime
モジュールには、日付オブジェクトに関する情報を返すための多くのメソッドがあります。
ここにいくつかの例があります。これらについては、この章の後半で詳しく説明します。
例
年と平日の名前を返します。
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
日付オブジェクトの作成
日付を作成するにdatetime()
は、モジュールのクラス(コンストラクター)を
使用できdatetime
ます。
このdatetime()
クラスでは、日付を作成するために、年、月、日という3つのパラメーターが必要です。
例
日付オブジェクトを作成します。
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
このdatetime()
クラスは、時間とタイムゾーン(時、分、秒、マイクロ秒、tzone)のパラメーターも受け取りますが、これらはオプションであり、デフォルト値は0
、(None
タイムゾーンの場合)です。
strftime()メソッド
datetime
オブジェクトには、日付オブジェクトを読み取り可能な文字列にフォーマットするためのメソッドがあります。
このメソッドはと呼ばれ、返される文字列の形式を指定するためにstrftime()
1つのパラメーターを取り
ます。format
例
月の名前を表示します。
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
すべての有効なフォーマットコードの参照:
Directive | Description | Example | Try it |
---|---|---|---|
%a | Weekday, short version | Wed | |
%A | Weekday, full version | Wednesday | |
%w | Weekday as a number 0-6, 0 is Sunday | 3 | |
%d | Day of month 01-31 | 31 | |
%b | Month name, short version | Dec | |
%B | Month name, full version | December | |
%m | Month as a number 01-12 | 12 | |
%y | Year, short version, without century | 18 | |
%Y | Year, full version | 2018 | |
%H | Hour 00-23 | 17 | |
%I | Hour 00-12 | 05 | |
%p | AM/PM | PM | |
%M | Minute 00-59 | 41 | |
%S | Second 00-59 | 08 | |
%f | Microsecond 000000-999999 | 548513 | |
%z | UTC offset | +0100 | |
%Z | Timezone | CST | |
%j | Day number of year 001-366 | 365 | |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 | |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 | |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 | |
%C | Century | 20 | |
%x | Local version of date | 12/31/18 | |
%X | Local version of time | 17:41:00 | |
%% | A % character | % | |
%G | ISO 8601 year | 2018 | |
%u | ISO 8601 weekday (1-7) | 1 | |
%V | ISO 8601 weeknumber (01-53) | 01 |