A set of examples using Python date and time functions, including formatting dates, date calculations and other bits in datetime package, similar to my string format examples. .
First off, all examples use the following import, any additional imports needed will be shown with the example.
from datetime import datetime
Creating Date Objects
# now now = datetime.now() # specific date dt1 = datetime(2011, 8, 29) dt2 = datetime(year=2012, month=3, day=2) # create a date from a known format str = "2012-10-20" dts = datetime.strptime(str, '%Y-%m-%d') # create a date from unix timestamp ts = 1294204471 dtu = datetime.fromtimestamp(ts)
Printing dates in various formats is relatively straight forward, here's one example. Refer to the table below for available formatting symbols and samples.
print dt1.strftime("%b %d, %Y") >> Jan 15, 1999
|%a||Weekday name abbreviated||Sun, Mon, Tue, ...|
|%A||Weekday name full||Sunday, Monday, Tuesday, ...|
|%b||Month name abbreviated||Jan, Feb, Mar, ...|
|%B||Month name full||January, February, ...|
|%c||A "random" date and time representation.||Fri Jan 15 16:34:00 1999|
|%d||Day of the month||[ 01, 31 ]|
|%f||Microsecond||[ 000000, 999999 ]|
|%H||Hour (24h)||[ 00, 23 ]|
|%I||Hour (12h)||[ 01, 12 ]|
|%j||Day of the year||[ 001, 366 ]|
|%m||Month||[ 01, 12 ]|
|%M||Minute||[ 00, 59 ]|
|%p||Locale's equivalent of either AM or PM.||[ AM, PM ]|
|%S||Second||[ 00, 61 ]|
|%U||Week number of the year (Sunday first)||[ 00, 53 ]|
|%w||Weekday number (Sunday=0)||[ 0, 6 ]|
|%W||Week number of the year (Monday first)||[0, 53 ]|
|%y||Year without century||[ 00, 99 ]|
|%Y||Year with century||1999|
|%z||UTC offset in the form +HHMM or -HHMM or empty string|
|%Z||Time zone name or empty string|
|%%||A literal '%' character.|
Date Calculations and Timedelta
from datetime import timedelta week_later = dt + timedelta(days=7) last_week = dt - timedelta(days=7) in_five_minutes = dt + timedelta(minutes=5)
Valid timedelta properties are:
weeks, days, hours, minutes, seconds, microseconds, milliseconds
You might notice that a "year" timedelta is absent, don't b tempted to do days=365, this would be off for leap-years. I would recommend something like the following:
start = datetime(year=2011, month=3, day=17) next_year = datetime(year=start.year+1, month=start.month, day=start.day)
Adding and Subtracting Dates
You can add and subtract date objects when doing so they return timedelta objects. Using the timedelta object, you can access the same properties above.
dt1 = datetime(year=2012, month=8, day=23) dt2 = datetime(year=2012, month=8, day=28) td = dt2 - dt1 td.days >> 5
Common Date Functions
Here are a few date functions which are commonly needed, I made the examples a little more explicit so it is easier to follow the calculation, you may want to shorten up some when used.
Last Day of the MonthTwo solutions, first using datetime and going to the first day of next month and subtracting a day.
Second solution to determine the last day of the month using the calendar object
from datetime import timedelta now = datetime.now() next_month = datetime(year=now.year, month=now.month+1, day=1) last_day_month = next_month - timedelta(days=1)
import calendar now = datetime.now() range = calendar.monthrange(now.year, now.month) last_day_month = now.replace(day=range)
today = datetime.now() thursday_dow = 4 today_dow = first_day_of_month.strftime("%w") adjustment = ( 7 + thursday_dow - int(today_dow)) % 7 next_thursday = today + timedelta(days=adjustment)
First Monday of the Month
today = datetime.now() first_day_of_month = today.replace(day=1) day_of_week = first_day_of_month.strftime("%w") adjustment = (8 - int(day_of_week) ) % 7 first_monday = first_day_of_month + timedelta(days=adjustment)