Operations Supported On Datetime Objects In Python

Subtraction of two datetime objects in Python:

  • It is allowed to subtract one datetime object from another datetime object
  • The resultant object from subtraction of two datetime objects is an object of type timedelta

Example:

import datetime

 

d1 = datetime.datetime.now()

d2 = datetime.datetime.now()

x  = d2-d1

print(type(x))

print(x)

 

Output:

<class 'datetime.timedelta'>

0:00:00.000008

 

  • The subtraction operation of two datetime objects succeeds, if both the objects are naive objects, or both the objects are aware objects. i.e., Both the objects have their tzinfo as None
  • If one datetime object is a naive object and another datetime  object is an aware object then  python raises an exception of type TypeError stating TypeError: can't subtract offset-naive and offset-aware datetimes.

Example:

 

import datetime

 

# Time difference for pacific time

pacificTimeDelta    = datetime.timedelta(hours=-8)

 

# Create a PST timezone in instance

tzPST        = datetime.timezone(pacificTimeDelta, name="PST")

 

# create a datetime for 1 PM PST - 31Dec2017 - An aware Object

OnePMyearEnd = datetime.datetime(2017,12,31,1,0,0,0,tzPST)

 

# create a dateobject for current time - without any timezone attached - A naive object

todaysDate = datetime.datetime.now()

 

# Try subtracting the naive object from the aware object

# This will raise a Type Error

todaysDate = OnePMyearEnd - todaysDate

 

 

Output:

todaysDate = OnePMyearEnd - todaysDate

TypeError: can't subtract offset-naive and offset-aware datetimes

 

  • If both the datetime objects are aware objects and each object is having a different time zone information – then both the time quantity of the objects are converted into UTC first and the subtraction is applied on the two UTC time quantities.

Example:

import datetime

 

# Time difference for pacific time

pacificTimeDelta    = datetime.timedelta(hours=-8)

 

# Create a PST timezone in instance

tzPST        = datetime.timezone(pacificTimeDelta, name="PST")

 

# create a datetime for 1 PM PST - 31Dec2017 - An aware Object

OnePMyearEndPST = datetime.datetime(2017,12,31,1,0,0,0,tzPST)

 

 

# Time difference for EST time

nycTimeDelta    = datetime.timedelta(hours=-8)

 

# Create a PST timezone in instance

tzEST           = datetime.timezone(nycTimeDelta, name="EST")

 

# create a datetime for 1 PM PST - 31Dec2017 - An aware Object

TwoPMyearEndEST = datetime.datetime(2017,12,31,2,0,0,0,tzEST)

 

print(TwoPMyearEndEST-OnePMyearEndPST)

 

 

Output:

1:00:00

 


Copyright 2023 © pythontic.com