Example 2: Date & Time

There are useful classes in the datetime module. For example:

Class Name Description Attributes
datetime.date An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. year, month, and day
datetime.time An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds (there is no notion of “leap seconds” here). hour, minute, second, microsecond, and tzinfo
datetime.datetime A combination of a date and a time. year, month, day, hour, minute, second, microsecond, and tzinfo
datetime.timedelta A duration expressing the difference between two date, time, or datetime instances to microsecond resolution. days, seconds, and microseconds

To use these classes, we need to import the datetime module first.

import datetime

To create a datetime.date, you need to have 3 arguments: year, month, and day for the constructor. The format is datetime.date(year, month, day). We can create an instance called my_birthday.

# create an instance of datetime.date
my_birthday = datetime.date(1980, 04, 01)

There is a class method called today(), which can return the current local date as a datetime.date object.

print my_birthday.today()
print type(my_birthday.today())
## result:
## 2014-10-28
## <type 'datetime.date'>

If we subtract my_birthday from my_birthday.today(), we can get an datetime.timedelta object, which stores the difference between the two date objects. Its days attribute can tell us how many days there are in the difference. And the total_seconds() method of datetime.timedelta can return the difference in seconds.

print "I have lived for",(my_birthday.today() - my_birthday).days, "days"
print "I have lived for",(my_birthday.today() - my_birthday).total_seconds(), "seconds"
## result:
## I have lived for 12628 days
## I have lived for 1091059200.0 seconds

It also has a instance method called weekday(), which returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

if my_birthday.weekday() >= 5:
    print "It is weekend."
else:
	print "It is not weekend"

The datetime.time class is similar to datetime.date, it has the attributes hour, minute, second, microsecond, and tzinfo. All the arguments are optional when you create the instance of datetime.time. The datetime.datetime class is a combination of a datetime.date and a datetime.time.
More information about classes in datetime module see: https://docs.python.org/2/library/datetime.html