アットウィキロゴ

日付

日付の取得方法は下記のように
「datetime」モジュールを使用する。
  1. #! c:/Python26/python.exe
  2. # -*- coding: utf-8 -*-
  3.  
  4. import datetime
  5.  
  6. if __name__ == "__main__":
  7.  
  8. today = datetime.date.today()
  9. todaydetail = datetime.datetime.today()
  10.  
  11. # 今日の日付
  12. print "--------------------------------------------"
  13. print today
  14. print todaydetail
  15.  
  16. # 今日に日付:それぞれの要素値
  17. print "--------------------------------------------"
  18. print today.year
  19. print today.month
  20. print today.day
  21. print todaydetail.year
  22. print todaydetail.month
  23. print todaydetail.day
  24. print todaydetail.hour
  25. print todaydetail.minute
  26. print todaydetail.second
  27. print todaydetail.microsecond
  28.  
  29. # 日付のフォーマット
  30. print "--------------------------------------------"
  31. print today.isoformat()
  32. print todaydetail.strftime("%Y/%m/%d %H:%M:%S")
  33.  


実行結果

2010-05-08
2010-05-08 15:42:00.731000

2010
5
8
2010
5
8
15
42
0
731000

2010-05-08
2010/05/08 15:42:00



日付の計算は「timedelta」を使用する。
「timedelta」では月の日数、うるう年なども気にする必要がない。
  1. #! c:/Python26/python.exe
  2. # -*- coding: utf-8 -*-
  3.  
  4. import datetime
  5.  
  6. if __name__ == "__main__":
  7.  
  8. today = datetime.datetime.today()
  9.  
  10. # 今日の日付
  11. print today
  12.  
  13. # 明日の日付
  14. print today + datetime.timedelta(days=1)
  15.  
  16. newyear = datetime.datetime(2010,1,1)
  17.  
  18. # 2010年1月1日の一週間後
  19. print newyear + datetime.timedelta(days=7)
  20.  
  21. # 2010年1月1日から今日までの日数
  22. calc = today - newyear
  23. # 計算結果の返り値は「timedelta」
  24. print calc.days
  25.  

実行結果
2010-05-08 15:36:24.006000
2010-05-09 15:36:24.006000
2010-01-08 00:00:00
127

タグ:

+ タグ編集
  • タグ:
最終更新:2013年03月24日 16:59