Replace Function In Python

Function Name:

replace

 

Function Signature:

date.replace(year, month, day)

 

Function Overview:

  • The replace() function of Python date object replaces specific values of a date object with the new values as specified by the year, month, day parameters in a newly created copy and returns it.
  • Note that the original date object is not changed by the replace() function.
  • While invoking replace() function either all the parameters can be specified or only one or more parameters can be specified.
  • The date object returned will have the new values reflected on it only for the parameters specified in the function call.

Example:

 

#import the python's datetime module

import datetime

 

# Create a date - new year

dateObject = datetime.date(2017, 1, 1)

 

print("New Year's day: {}".format(dateObject))

 

# 2nd day of the year can be arrived by just changing only the date on the new year's date

dateObject1 = datetime.date(2017, 1, 2)

 

print("Second day of the year: {}".format(dateObject))

 

# Change the date object to hold the value of Independence Day celebrations 2018

dateObject2 = dateObject.replace(year=2017, month=7, day=4)

print("Independece day: {}".format(dateObject))

 

# Change the date object to hold the value of Thanks giving Day

dateObject3 = dateObject.replace(year=2017, month=11, day=23)

print("Thanks Giving day: {}".format(dateObject))

 

# The original date object is not changed by the replace() function

print("Original Date object:{}".format(dateObject))

 

Output:

New Year's day: 2017-01-01

Second day of the year: 2017-01-01

Independece day: 2017-01-01

Thanks Giving day: 2017-01-01

Original Date object:2017-01-01

 


Copyright 2023 © pythontic.com