Datetime.replace() Function In Python

Function Name:

replace

 

Function Signature:

replace()

 

Function Overview:

  • The function replace() is to replace specific or all the attributes of a datetime object.

 

  • Date attributes of a datetime object that can be replaced by the replace() function:
    • year
    • month
    • day

 

  • Time attributes of a datetime object that can be replaced by the replace() function:
    •     hour
    •     minute
    •     second
    •     microsecond

 

  • Attributes related to the timezone information that can be replaced
    •  tzinfo

 

  • DST attributes that can be replaced by the replace function:
    •     fold

 

Example:

import datetime

 

# New year's eve of 2020

newYearEve2020 = datetime.datetime(2019, 12, 31, 12, 59, 59, 99)

 

# Make it the next day by calling replace function

newYearDate2020 = newYearEve2020.replace(2020, 1, 1, 00, 00, 00, 00)

 

print("2020 New year's eve {}".format(newYearEve2020))

print("2020 New year {}".format(newYearDate2020))

 

# Make the new year date timezone aware

estTimeDelta    = datetime.timedelta(hours=-5)

 

# Create a timezone instance for EST

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

 

newYearDate2020EST = newYearEve2020.replace(2020, 1, 1, 00, 00, 00, 00,tzObject)

 

print("2020 New year in EST:{}".format(newYearDate2020EST))

 

#create a timedate object using splat operator

timeDateTuple       = (2020, 1, 2, 00, 00, 00, 00)

newYearNextDay2020  = newYearDate2020EST.replace(*timeDateTuple)

print("2020 new year next day in EST:{}".format(newYearNextDay2020))

 

Output:

2020 New year's eve 2019-12-31 12:59:59.000099

2020 New year 2020-01-01 00:00:00

2020 New year in EST:2020-01-01 00:00:00-05:00

2020 new year next day in EST:2020-01-02 00:00:00-05:00

 


Copyright 2023 © pythontic.com