Tips Tricks Tutorials


Learn Tips and tricks on Linux, Hacking, linux, PHP, Perl, Web, Hardware

bookmark bookmark
WEBNESBAY On October - 19 - 2009

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 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

Tips on date time module

  • datetime.strptime silently 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
  • is never to be used. Always use datetime.utcnow()
  • 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:


Related posts:

  1. Quick tutorial for handling exceptions in python
  2. PHP Cookies tutorial a quick guide
  3. Type Checking in Python
  4. Top 10 php optimization tips
  5. User defined exceptions in python
Categories: Python

One Response

  1. Russel says:

    I really liked your blog! good

Leave a Reply

Easy AdSense by Unreal