The datetime module provides a number of types to deal with dates, times, and time intervals. This module replaces the integer/tuple-based time mechanisms in the time module with a more object-oriented interface. All types provided by this module are new-style classes, and can be subclassed and extended from Python.

Representation

datetime module represented in ISO 8601 formatted

1

2

2007-03-0420:32:17

20070304T203217

The datetime module exports the following constants:

MINYEAR : The smallest year number allowed in a date or datetime object. MINYEAR is 1.

MAXYEAR : The largest year number allowed in a date or datetime object. MAXYEAR is 9999.

Available Types

The module contains the following types:

The datetime type gives output of date and time during the day. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.

The date type contains date between year 1 and 9999. Attributes: year, month, and day.

The time type shows time, independent of the date. Attributes: hour, minute, second, microsecond, and tzinfo.

The timedelta shows duration expressing the difference between two date, time, or datetime instances to microsecond resolution

The tzinfo type is used to implement timezone support. Time zone displays in UTC format

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import datetime

import time

print datetime.datetime(2009,10,19,21,41,43)

print datetime.datetime.today()

print datetime.datetime.now()

print datetime.datetime.utcnow()

print datetime.datetime.utcfromtimestamp(time.time()).

Output

2009-10-1921:41:43

2009-10-1911:51:24.670136

2009-10-1911:51:24.670172

2009-10-1906:21:24.670195

2009-10-1906:21:24.670206

Tips on date time module

datetime.strptimesilently throws away all timezone information. If you look very closely, it even says so in its documentation

Timezones do not exist, all datetime objects have to be naive. aware means broken.

datetime objects must always contain UTC information

datetime.now() is never to be used. Always use datetime.utcnow()

Be careful of 3rd party python modules: people have a dangerous tendency to use datetime.now()

If a conversion to some local time is needed, it shall be done via either some ugly thing like time.localtime(int(dt.strftime("%s"))) or via the pytz module

pytz must be used directly, and never via timezone aware datetime objects, because datetime objects fail in querying pytz: