Index > Pythonによる日付操作(python,date)
Fri, January 23, 2009

Pythonによる日付操作(python,date)

Pythonによる日付操作のメモ。

今日の日付を取得

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> print now
2009-01-24 07:20:46.881875
>>> print now.year
2009
>>> print now.month
1
>>> print now.day  
24

一日前の日付を取得する方法

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> print now
2009-01-24 07:20:46.881875
>>> yesterday = now-timedelta(1)
>>> print yesterday
2009-01-23 07:20:46.881875

文字列から日付オブジェクトを生成

>>> import time
>>> from datetime import datetime
>>> date="2009-01-30"
>>> st=time.strptime(date,'%Y-%m-%d')
>>> dt=datetime(st.tm_year, st.tm_mon, st.tm_mday)
>>> print dt
2009-01-30 00:00:00
 Twitter
follow me on Twitter
 Categories