Date has only date (year, month, day) but not time.

from datetime import date

DateTime includes all including time.

from datetime import datetime

Get current datetime

>>> import datetime

Get yesterday


from datetime import date,timedelta - timedelta(days=1)

Get number of days in a month

from calendar import monthrange
month, days= monthrange(2011, 2)
print days

Timezone aware datetime

# in shell, install pytz first
$ pip install pytz

# in python source code
import pytz

Convert Epoch to Date

from datetime import datetime
print dt.year, dt.month,
print dt.isoformat() --> 2007-11-06T07:05:12

Convert string to datetime

from datetime import datetime
  • Date does NOT have strptime() although it has strftime()

Ignore certain fields (

val = str.join(' ', 'Wed, 17 Oct 2011 22:22:22 +0300'.split()[1:7])
val = datetime.datetime.strptime(val, '%d %b %Y %H:%M:%S')

Also I’d use split() to split into list items and then use range to eliminate 1st element. Then join(' ', str) to reconstitute it.

  • alternative is to use regex or other parsing tool

Convert to string

Convert to string using strftime()

print mydate.strftime("%m/%d/%Y %A")

%d: day (01-31)
%m: month (01-12)
%Y: year (2015)
%y: year (15)
%A: Day of the week (Monday)
%w: 0-6, Sunday=0 *this differs from "weekday()"
%H: hour
%M: Minute
%S: seconds 00-59

Convert to string using format()

print "day:{0:%d} year:{0:%Y}".format(d)  #d= datetime

d.month : 1-12 1-31
d.weekday() # returns 0-6, but 0=Monday, not Sunday!  this contradicts "%w"