Python datetime
module handles the extraction and formatting of date and time variables.
datetime
module includes five classes: date, time, datetime, timedelta and tzinfo. Objects of these
objects are immutable.
• date Objects:
>>> from datetime import date >>> d = date.today() >>> d
dateimt.date(2012, 12, 11)
>>> d2 = date(2000, 3, 14) >>> d2.year
2000
>>> d2.month
3
>>> d2.day
14
>>> if (d > d2): ... print(abs(d-d2)) ...
4875 days, 0:00:00• time Objects:
>>> from datetime import time >>> t = time(3, 12, 2) >>> t
datetime.time(3,12,2)
>>> t.strftime("%H:%M:%S")
'03:12:02'
>>> t.strftime("%H hour %M minute %s seconds")
'03 hour 12 minute 02 seconds'• datetime Objects: this object has combined information from date and time object.
>>> from datetime import datetime, date, time >>> d = date(2000, 3, 14) >>> t = time(3, 12, 2) >>> dt = datetime.combine(d,t) >>> dt
datetime.datetime(2000, 3, 14, 3, 12, 2)
>>> datetime.now()
datetime.datetime(2012, 12, 11, 6, 7, 16, 542132)
>>> datetime.utcnow()
datetime.datetime(2012, 12, 11, 10, 10, 16, 274808)
>>> dt2 = datetime.strptime("12/11/2012 07:10", "%d/%m/%Y %H:%M") >>> dt2.year
2012
>>> dt2.month
12
>>> dt2.day
11
>>> dt2.hour
7
>>> dt2.minute
10
>>> dt2.second
0
>>> dt2.weekday()
0• timedelta Objects: handles date/time differences.#0:Monday, 1:Tuesday, 2:Wednesday ...
>>> from datetime import timedelta >>> y = timedelta(days=5, hours=2, minutes=10, seconds=21) >>> y2 = timedelta(days=21, hours=21, minutes=15, seconds=3) >>> y3 = y2 - y >>> y3
datetime.timedelta(16, 68682)
>>> y3.days
16
>>> y3.seconds
68682• tzinfo class: abstract class handling time zone information.
>>> from datetime import tzinfo, timedelta, date, time, datetime >>> class GMT_4(tzinfo): ... def utcoffset(self, dt): ... return timedelta(hours=-4) ... def tzname(self, dt): ... return "America/New_York" ... >>> t = time(14,4,21,tzinfo=GMT_4())
'14:04:21-04:00'