Top / Programming / Python / Python CGIプログラミング入門 / 現在の日時を表示する

現在の日時を表示する

現在の日時を出力します。

test02.cgi

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
現在の日時を表示する
'''

html = '''Content-Type: text/html

<html>
<head>
  <title>現在の日時を表示する</title>
</head>
<body>
<h1>現在の日時を表示する</h1>
<p>現在の日時は、「%s」です。</p>
</body>
</html>
'''

import time
now = time.strftime('%Y年%m月%d日 %H時%M分%S秒')
print html % now

解説

1行目から5行目までは、前回と同じです。

html = '''Content-Type: text/html

<html>
<head>
  <title>現在の日時を表示する</title>
</head>
<body>
<h1>現在の日時を表示する</h1>
<p>現在の日時は、「%s」です。</p>
</body>
</html>
'''

6行目から17行目では、変数 html に出力する文字列を代入します。

HTML文書を出力するので、Content-Type には text/html を指定します。

14行目の %s は文字列フォーマットです。現在日時と置き換えます。

import time
now = time.strftime('%Y年%m月%d日 %H時%M分%S秒')

timeモジュールをロードし、変数 now に現在日時を整形して代入します。

print html % now

変数 html の %s に 変数 now の値を入れて出力します。

更新履歴