Wednesday, January 05, 2011

Python Date Operations

Get current time:
>>> import datetime
>>> datetime.date.today()
datetime.date(2011, 1, 12)
>>> datetime.datetime.now()
datetime.datetime(2011, 1, 12, 20, 36, 21, 430985)

Adding time and timedelta:
>>> datetime.timedelta(hours=7) + datetime.datetime(2011,1,1)
datetime.datetime(2011, 1, 1, 7, 0)
>>> datetime.timedelta(days=50) + datetime.date(2011,1,1)
datetime.date(2011, 2, 20)

Subtracting dates:
>>> datetime.date(2011,1,2) - datetime.date(2011,1,1)
datetime.timedelta(1)

Convert date and time into datetime:
>>> import datetime
>>> d = datetime.date(2010,01,05)
>>> t = datetime.time(10,25)
>>>datetime.datetime.combine(d,t)
datetime.datetime(2010, 1, 5, 10, 25)

Convert String to datetime:
>>> datetime.datetime.strptime("2011-01-05","%Y-%m-%d")
datetime.datetime(2011, 1, 5, 0, 0)

Convert datetime to individual components:
 >>> dt = datetime.datetime(2011,01,05,12,00)
>>> (dt.year, dt.month, dt.day, dt.hour, dt.minute)
(2011, 1, 5, 12, 0)

Convert datetime to date:
 >>> dt = datetime.datetime(2011,01,05,12,00)
>>> dt.date()
datetime.date(2011, 1, 5)

Add one day to a date:
>>> dt = datetime.datetime(2011,01,05,12,00)
>>> delta = datetime.timedelta(days=1)
>>> dt + delta
datetime.datetime(2011, 1, 6, 12, 0)

Number of days in a month:
>>> import calendar
>>> calendar.monthrange(2011,1)
(5, 31)

Timezone
from pytz import timezone as tz
localtz = tz('US/Central')
#dt_aware = localtz.localize(dt_unaware)
dt_unaware.replace(tzinfo=localtz)


more to come...

No comments: