Python dates

From Noah.org
Revision as of 19:28, 27 February 2008 by Root (talk | contribs)
Jump to navigationJump to search

Python has built-in support for doing date arithmetic. Here are some exercises:

import datetime

year = '2008'
month = '1'
day = '24'

# This shows how to create a datetime object based on 32 days in the past.
last_month = datetime.datetime.now() - datetime.timedelta(days=32)
# This creates a datetime object from the now time.
now = datetime.datetime.now()
# Make some other datetime from strings. I do this if I parse dates from a string.
other_date = datetime.datetime(year=int(year), month=int(month), day=int(day))
# This does some simple date arithmetic to calculate how many days old something is.
if (now - other_date).days > 31:
    print "Older than a month."