Apr 8, 2013 python

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
>>> datetime.datetime.now()

Get yesterday

datetime.date.fromordinal(datetime.date.today().toordinal()-1)

OR

from datetime import date,timedelta
date.today() - 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
now=datetime.now(pytz.utc)

Convert Epoch to Date

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

Convert string to datetime

from datetime import datetime
mydate=datetime.strptime("2012-01-01","%Y-%m-%d")

Ignore certain fields (http://stackoverflow.com/a/8558956/1673809)

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.

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
d.day: 1-31
d.year
d.weekday() # returns 0-6, but 0=Monday, not Sunday!  this contradicts "%w"