Python Combining Date & Time

We can create 'datetime' class object by combining date class object and time class objects using combine() method. Please remember that the date and time classes belong to 'datetime' module. For example, we can create a date class object with some date as:

d = date(2016, 4, 29)

Similarly, we can create time class object and store some time as:

t = datetime.time(15, 30)

Now, the combine() method is a class method in the class 'datetime' that can combine the previously created objects as:

dt = datetime.combine(d, t)

Combining date and time objects

CopiedCopy Code

#combining date and time 
from datetime import * 
d = date(2020, 4, 29) 
t = time(15, 30) 
dt = datetime.combine(d, t) 

The second way of creating 'datetime' object is by using combine() method as:

dt2 = datetime.combine(d, t)

The third way of creating 'datetime' object is by directly creating the object and passing the date and time values as:

dt3 = datetime(year=2020, month=6, day=24)

dt4 = datetime(2020, 6, 24, 18, 30)

dt5 = datetime(year=2020, month=6, day=24, hour=15, minute=30)

We can change the content of the 'datetime' object by calling replace() method on the object as:

dt6 = dt5.replace(year=2017, month=10)

Custom Date and time

CopiedCopy Code

#creating datetime object and change its contents 
from datetime import * 
#create a datetime object 
dt1 = datetime(year=2016, month=6, day=24, hour=15, minute=30, second=15) 
#change its year, month and hour values 
dt2 = dt1.replace(year=2017, hour=20, month=10)