pythonのdatetimeオブジェクトについて

map IT

datetimeオブジェクトはdatetimeモジュールで使用できる日時を表現するオブジェクトで、日付や時間を個別に指定、出力することができます。

スポンサーリンク

datetimeオブジェクトの作成

datetime python1
datetimeオブジェクトを使用するには、最初にdatetimeモジュールをimportする必要があります。
#python
import datetime
d = datetime.datetime(2022,1,1,1,1,1,1)
print(d)
datetime.datetimeは、年、月、日、時、分、秒、マイクロ秒、タイムゾーンの情報を持ちます。
たとえばこんな感じでマイクロ秒まで指定すると、
datetime python2
こんな感じで指定日時のdatetimeオブジェクトが作成できます。
datetime python3
時間以降は省略も可能です。
#python
import datetime
d = datetime.datetime(2022,1,1)
print(d.year)
print(d.month)
print(d.day)
print(d.hour)
print(d.minute)
print(d.second)
print(d.microsecond)
print(d.tzinfo)
datetimeオブジェクトの日時日付などは個別に取得することも可能です。
datetime python4
実行結果です。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny