Introduction to Datetime module
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.
datetime module represented in ISO 8601 formatted
The datetime module exports the following constants:
MINYEAR : The smallest year number allowed in a date or datetime object. MINYEAR is
- MAXYEAR : The largest year number allowed in a date or datetime object. MAXYEAR is
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
print datetime.datetime(2009, 10, 19, 21, 41, 43)
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
- Be careful of 3rd party python modules: people have a dangerous tendency to use
- 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: