>>> import datetime >>> datetime.datetime.now() datetime.datetime(2012, 10, 23, 20, 33, 21, 723000) >>> datetime.datetime.utcnow() datetime.datetime(2012, 10, 23, 11, 40, 9, 398000)
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt datetime.datetime(2000, 1, 2, 3, 4, 5, 6)
時・分・秒・マイクロ秒は省略可能
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt.year 2000 >>> dt.month 1 >>> dt.day 2 >>> dt.hour 3 >>> dt.minute 4 >>> dt.second 5 >>> dt.microsecond 6 >>> dt.weekday() 6
dt.weekday() は、0(月曜)〜6(日曜)
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt + datetime.timedelta(days=30) datetime.datetime(2000, 2, 1, 3, 4, 5, 6) >>> dt - datetime.timedelta(days=-30) datetime.datetime(2000, 2, 1, 3, 4, 5, 6) >>> dt - datetime.timedelta(days=30) datetime.datetime(1999, 12, 3, 3, 4, 5, 6)
datetime.timedelta() には、days, seconds, microseconds, milliseconds, minutes, hours, weeks が設定可能。(year, month は設定できない)
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt2 = datetime.datetime(2001,2,3,4,5,6,7) >>> delta = dt2 - dt >>> delta datetime.timedelta(398, 3661, 1) >>> delta.days 398 >>> delta.seconds 3661 >>> delta.microseconds 1 >>> delta.total_seconds() 34390861.000001
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt2 = datetime.datetime(2001,2,3,4,5,6,7) >>> dt3 = datetime.datetime(1999,1,2,3,4,5,6) >>> dt3 = dt3 + datetime.timedelta(days=365) >>> dt < dt2 True >>> dt == dt3 True
>>> import datetime >>> dt = datetime.datetime(2000,1,2,3,4,5,6) >>> dt.strftime('%Y年%m月%d日 %H時%M分%S秒 %Z') '2000年01月02日 03時04分05秒 ' >>> dt.strftime('%b-%d-%Y (%a) %I:%M:%S %p') 'Jan-02-2000 (Sun) 03:04:05 AM'