Pythonで日時/時刻を取得するサンプルプログラム


Pythonで日時/時刻を取得するサンプルプログラムのソースコードになります。

こちらは拙著「スマホでPythonをはじめよう / Androidスマートフォン と Termux アプリを使ったプログラミング入門&学習」の【サンプルプログラム1】です。

Pythonで日時/時刻を取得するサンプルプログラム:ソースコード


import datetime

now=datetime.datetime.now()#時刻を取得

#曜日を取得するパート(ココは曜日が必要ない場合はカットしてOK)
day_list = [['Monday','(月)'],['Tuesday','(火)'],['Wednesday','(水)'],['Thursday','(木)'],['Friday','(金)'],['Saturday','(土)'],['Sunday','(日)']]
for x in range(7):
    if now.strftime('%A') == day_list[x][0]:
        youbi = day_list[x][1]
#↑ ここまで曜日を取得するパート(曜日が必要ない時はカットOK)

#年/月/日
now_1 = now.strftime('%y%m%d')#西暦2桁表記数字
now_2 = now.strftime('%Y%m%d')#西暦4桁数字
now_3 = "{0.year}/{0.month}/{0.day}".format(now)# / 
now_4 = "{0.year}/{0.month}/{0.day}{1}".format(now,youbi)# / 曜日
now_5 = now.strftime('%Y/%m/%d')# / 0あり(07/24etc)
now_6 = now.strftime('%Y/%m/%d{}'.format(youbi))# / 0あり・曜日
now_7 = "{0.year}-{0.month}-{0.day}".format(now)# -
now_8 = "{0.year}-{0.month}-{0.day}{1}".format(now,youbi)# - 曜日
now_9 = now.strftime('%Y-%m-%d')# - 0あり(07/24etc)
now_10 = now.strftime('%Y-%m-%d{}'.format(youbi))# - 0あり・曜日
now_11 = "{0.year}年{0.month}月{0.day}日".format(now)#漢字年月日
now_12 = "{0.year}年{0.month}月{0.day}日{1}".format(now,youbi)#漢字年月日・曜日
now_13 = now.strftime('%Y年%m月%d日')# 0あり・漢字年月日
now_14 = now.strftime('%Y年%m月%d日{}'.format(youbi))# 0あり・漢字年月日・曜日

#年/月/日/時/分
now_15 = "{0.year}/{0.month}/{0.day} {0.hour}:{0.minute}".format(now)# /
now_16 = "{0.year}/{0.month}/{0.day}{1} {0.hour}:{0.minute}".format(now,youbi)# / 曜日
now_17 = now.strftime('%Y/%m/%d %H:%M')# / 0あり(07/24etc)
now_18 = now.strftime('%Y/%m/%d{} %H:%M'.format(youbi))# / 0あり・曜日
now_19 = "{0.year}年{0.month}月{0.day}日{0.hour}時{0.minute}分".format(now)#漢字年月日
now_20 = "{0.year}年{0.month}月{0.day}日{1} {0.hour}時{0.minute}分".format(now,youbi)#漢字年月日・曜日
now_21 = now.strftime('%Y年%m月%d日 %H時%M分')# 0あり・漢字年月日
now_22 = now.strftime('%Y年%m月%d日{} %H時%M分'.format(youbi))# 0あり・漢字年月日・曜日

#年/月/日/時/分/秒
now_23 = "{0.year}年{0.month}月{0.day}日{0.hour}時{0.minute}分{0.second}秒".format(now)#漢字年月日
now_24="{0.year}年{0.month}月{0.day}日{1} {0.hour}時{0.minute}分{0.second}秒".format(now,youbi)#漢字年月日・曜日


#ここから出力(プリントアウト)部分
print('\nデフォルト')
print(now)#デフォルト
print('\n')
print('年/月/日')
print(now_1)
print(now_2)
print(now_3)
print(now_4)
print(now_5)
print(now_6)
print(now_7)
print(now_8)
print(now_9)
print(now_10)
print(now_11)
print(now_12)
print(now_13)
print(now_14)
print('\n')
print('年/月/日/時/分')
print(now_15)
print(now_16)
print(now_17)
print(now_18)
print(now_19)
print(now_20)
print(now_21)
print(now_22)
print('\n')
print('年/月/日/時/分/秒')
print(now_23)
print(now_24)
print('\n')


解説および使い方については、書籍内で行っておりますので、そちらを参考にしていただけると嬉しいです。

この記事が気に入ったらサポートをしてみませんか?