3.3. 日付・時間

3.3.1. 日付・時間の取得

日付の取得方法は下記の通りです。 標準ライブラリである「datetime」を使用しましょう。※標準ライブラリで特定の機能を使用したい場合はこのように「import」を用います。「str(\'a\')」や「int(\'1\')」は「import」を行わずに使うことができます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 import datetime


 today        =    datetime.date.today()
 todaydetail  =    datetime.datetime.today()

 # 今日の日付
 print ('--------------------------------------------')
 print (today)
 print (todaydetail)

 # 今日に日付:それぞれの値
 print ('--------------------------------------------')
 print (today.year)
 print (today.month)
 print (today.day)
 print (todaydetail.year)
 print (todaydetail.month)
 print (todaydetail.day)
 print (todaydetail.hour)
 print (todaydetail.minute)
 print (todaydetail.second)
 print (todaydetail.microsecond)

 # 日付のフォーマット
 print ('--------------------------------------------')
 print (today.isoformat())
 print (todaydetail.strftime("%Y/%m/%d %H:%M:%S"))

出力

--------------------------------------------
2017-11-17
2017-11-17 04:18:02.081344
--------------------------------------------
2017
11
17
2017
11
17
4
18
2
81344
--------------------------------------------
2017-11-17
2017/11/17 04:18:02

3.3.2. 日付の計算

日付の計算は「timedelta」を使用します。 「timedelta」は月の日数、うるう年なども気にしないでよいので、自分で計算するより手間を省くことができます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import datetime


today = datetime.datetime.today()

# 今日の日付
print (today)

# 明日の日付
print (today + datetime.timedelta(days=1))

newyear = datetime.datetime(2018, 1, 1)

# 2018年1月1日の一週間後
print (newyear + datetime.timedelta(days=7))

# 2018年1月1日から今日までの日数
calc = today - newyear

# 計算結果の戻り値は「timedelta」
print (calc.days)

出力

2018-05-08 15:36:24.006000
2018-05-09 15:36:24.006000
2018-01-08 00:00:00
127

3.3.3.  うるう年の判定

その年がうるう年かどうかを判定するには「calendar.isleap」を、指定期間内に何回のうるう年があるかを取得するには「calendar.leapdays」を使用します。

1
2
3
4
5
6
7
import calendar

print (calendar.isleap(2015))
print (calendar.isleap(2016))
print (calendar.isleap(2017))

print (calendar.leapdays(2018, 2020))

出力

False
True
False
2