Python で Datetime オブジェクトから年を取得する

Fariba Laiq 2022年4月8日
Python で Datetime オブジェクトから年を取得する

datetime オブジェクトから年を取得します。基本的に、datetime は、日付と時刻を処理するクラスで構成されるモジュールです。日付の作成、保存、アクセス、フォーマットなどを行うことができます。

Python の datetime オブジェクトから年を取得する

datetime オブジェクトから年を取得する手法は非常に簡単です。datetime オブジェクトには、年、月、日、時、分、秒などの特定の属性があります(入力日の形式によって異なります)。

datetime オブジェクトの year 属性にアクセスし、日付から年を取得します。この例では、今日の日付(現在の日付)から年を取得します。より明確な例として、日、月、年を含む今日の日付を出力します。次に、datetime オブジェクトの year 属性にアクセスし、それを出力します。

サンプルコード:

# python 3.x
import datetime
date = datetime.date.today()
print("Date is:", date)
year=date.year
print("Year of the Date is:", year)

出力:

Date is: 2021-12-05
Year of the Date is: 2021
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

関連記事 - Python DateTime