Datetime class in Python

Overview:

The Python datetime class represents the following information together:

  • Date
  • Time
  • TimeZone - Either None or a valid tzinfo object

   

Since the datetime class can contain time zone information as well, date time instances are potential "aware" objects when compared to “naive” objects like date objects, which do not have time zone information.

 

Similar to date objects, which extend the Gregorian calendar, for pre-gregorian dates and future dates as well the datetime objects also extend to the pre-Gregorian dates and future dates.

 

Similar to date objects datetime objects as well exactly have 86400 seconds in a day.

 

Creating datetime objects:

Python datetime objects can be created using several ways.

 

Using datetime constructor:

 

The datetime constructor takes the following components and constructs a datetime object.

    - year

    - month

    - day

    - hour                       : with the default value of zero

    - minute                   : with the default value of zero

    - second                  : with the default value of zero

    - microsecond        : with the default value of zero

    - tzinfo                    : with None as default value

    - fold                       : Zero by default

Example

import datetime

 

# Create a timedelta with the number of hours CST is behind UTC

cstTimeDelta    = datetime.timedelta(hours=-6)

 

# Create a timezone instance for CST

tzObject        = datetime.timezone(cstTimeDelta, name="CST")

 

# Create an arbitrary date, time in CST

datetimeObject = datetime.datetime(2017,2,22,12,55,55,99,tzObject)

 

print(datetimeObject)

 

Output:

2017-02-22 12:55:55.000099-06:00

 

Using an existing datetime object:

A datetime object can be created from a tuple of required values. The splat operator * can be used to unpack a tuple as given in the python example below:

 

Example:

 import datetime

 

# Create a timedelta with the number of hours PST is behind UTC

pstTimeDelta    = datetime.timedelta(hours=-8)

 

# Create a timezone instance for PST

tzObject        = datetime.timezone(pstTimeDelta, name="PST")

 

# Create an arbitrary date, time in PST

datetimeTuple = (2018,3,22,12,59,59,999,tzObject)

 

# Create another datetime instance by unpacking datetimeTuple with splat operator

datetimeObject = datetime.datetime(*datetimeTuple)

 

print(datetimeObject)

 

The above Python statement will create a datetimeObject from a tupe of values datetimeTuple.

 

Creating datetime object from today's date:

Creating a datetime object with today's date is done with invoking the today() class method of datetime class.

 

Example:

import datetime

 

# This will create a datetime object with today's date

todaysDate = datetime.datetime.today()

print(todaysDate)

Output:

2017-02-12 11:17:58.049658

 

 

Creating datetime object from current time and date:

The class method now() of Python datetime class creates a datetime instance with the current time and date.  A tzinfo object can be passed inside now() if an “aware” object is required.

 

Example:

 

import datetime

 

# This will create a datetime object with current time and date

dateWithCurrentTime = datetime.datetime.now()

print(dateWithCurrentTime)

 

Output:

2017-02-12 11:27:34.775818

 

Creating a datetime object from current UTC time:

The class method utcnow()of datetime class creates a datetime instance initialized with the current UTC time.

 

Note that the object created is still a “naive” object. It does not hold any tzinfo instance denoting UTC time.

Example:

import datetime

 

# Create a datetime object from current UTC time

dateTimeFromUTC = datetime.datetime.utcnow()

print(dateTimeFromUTC)

 

# Still a naive object?

print(dateTimeFromUTC.tzinfo)

 

Output:

2017-02-12 06:01:38.167721

None

 

 

Creating a datetime object from POSIX timestamp:

A datetime object can be created from a POSIX timestamp, by calling fromtimestamp() class method of datetime.

 

A POSIX timestamp is number of seconds elapsed from midnight 00:00:00 UTC on 1 January 1970.  fromtimestamp()creates either a naive object or an aware object based on the tzinfo passed.

 

 

Example:

import datetime

 

# this will create a naive datetime using the timestamp provided

naiveObject = datetime.datetime.fromtimestamp(1486828798)

print(naiveObject)

print(naiveObject.tzinfo)

 

# this will create a datetime for EST with the timestamp provided

estTimeDelta        = datetime.timedelta(hours=-5)

tzObject            = datetime.timezone(estTimeDelta, name="EST")

estDateTimeObject   = datetime.datetime.fromtimestamp(1486828798, tzObject)

 

print(estDateTimeObject)

print(estDateTimeObject.tzinfo)

 

Example:

2017-02-11 21:29:58

None

2017-02-11 10:59:58-05:00

EST

 

 

Creating datetime object from proleptic Gregorian Ordinal:

A proleptic Gregorian Ordinal defines the number of days from the date 01Jan01.

It is proleptic because the Gregorian calendar is followed from October 1582 only.

 

A datetime object can be created from a proleptic Gregorian Ordinal

using the class method fromordinal() of datetime class.

Example:

import datetime

 

gregorianOrdinal    = 123456

somePastDate        = datetime.datetime.fromordinal(gregorianOrdinal)

print(somePastDate)

 

Output:

0339-01-05 00:00:00

 

Creating a datetime object by combining a date object and time object:

A date object and a time object can be combined to form a datetime object.

The resultant datetime object will have date attributes from the date object

and the time attributes  from the time object.

 

Based on tzinfo passed the datetime object is either a “naive“ object or an “aware“ object.

 

Example:

import datetime

 

dateObject     = datetime.date(2017, 5, 15)

timeObject     = datetime.time()

 

# Create a timedelta with the number of hours AEDT is behind UTC

sydneyTimeDelta    = datetime.timedelta(hours=-11)

 

# Create a timezone instance for AEDT

tzObject            = datetime.timezone(sydneyTimeDelta, name="AEDT")

 

 

datetimeObject = datetime.datetime.combine(dateObject, timeObject, tzObject) 

print(datetimeObject)

print(datetimeObject.tzinfo)

 

Output:

2017-05-15 00:00:00-11:00

AEDT1

 


Copyright 2024 © pythontic.com