Python datetime.time.replace() Method

Vaibhav Vaibhav Jan 30, 2023
  1. Syntax
  2. Example 1: Use datetime.time.replace() to Modify Time and Timezone Details
  3. Example 2: Use datetime.time.replace() to Convert a Timezone-Aware time to a Naive Instance
Python datetime.time.replace() Method

Python is a dynamic and popular general-purpose programming language. It is enriched with numerous use cases, has access to various third-party libraries, and has a ton of support from its community.

It offers multiple built-in modules, one of them being the datetime module, which makes working with date, time, and time zones a piece of cake.

This module offers methods and classes such as date, datetime, tzinfo, timezone, and timedelta to work with date and time. These classes are flooded with numerous functions and attributes and deliver robust features.

The datetime module offers a time class that can describe time. Every object of this class has access to an instance method, replace().

This method lets us manipulate attributes of the time instance and create a new instance out of it. Note that these changes are applied to the new instance, not the original one.

In this article, we will cover this method in detail with the help of some relevant examples.

Syntax

time.replace(
    hour=self.hour,
    minute=self.minute,
    second=self.second,
    microsecond=self.microsecond,
    tzinfo=self.tzinfo,
    fold=0,
)

Parameters

Parameters Type Description
hour Integer An hour value between 0 and 23, inclusive.
minute Integer A minute value between 0 and 59, inclusive.
second Integer A second value between 0 and 59, inclusive.
microsecond Integer A microsecond value between 0 and 999999, inclusive.
tzinfo A subclass of datetime.tzinfo A concrete class subclassing the abstract datetime.tzinfo class.
fold Integer A binary field representing an invalid date. Here, 1 means an invalid date.

Returns

The replace() method returns a new time object with all the same attributes as the original time object, except for those attributes for which new values were provided.

Note that if tzinfo is set to None, a timezone-unaware datetime object is returned for which no conversions are performed for time values.

By default, for naïve or timezone-unaware objects, time is stored according to UTC or Coordinated Universal Time.

Example 1: Use datetime.time.replace() to Modify Time and Timezone Details

import datetime

cet = datetime.timezone(datetime.timedelta(hours=2), name="CET")
ist = datetime.timezone(datetime.timedelta(hours=5, minutes=30), name="IST")
time = datetime.time(12, 33, 45, 234154, cet)
print("Time:", time)
print("Timezone:", time.tzname())
print("Changed Time:", time.replace(hour=10, minute=11, second=30, microsecond=999999))
time = time.replace(tzinfo=ist)
print("Time:", time)
print("Changed Timezone:", time.tzname())

Output:

Time: 12:33:45.234154+02:00
Timezone: CET
Changed Time: 10:11:30.999999+02:00
Time: 12:33:45.234154+05:30
Changed Timezone: IST
  1. The Python code above first creates two timezone objects for the CET and IST timezone.
  2. Next, it creates a timezone-aware time object and sets its timezone to CET. We can confirm the timezone name using the instance method, tzname(), which returns the name of the timezone on a time object.
  3. Next, we update the time using the replace method. A new object is created, and the print() prints the object.
  4. Next, we update the timezone to the IST timezone. Note that only the timezone got updated; the time values were not adjusted.

The time changed from 12:33:45.234154+02:00 to 12:33:45.234154+05:30. The tzname() method verifies that the timezone is IST.

Example 2: Use datetime.time.replace() to Convert a Timezone-Aware time to a Naive Instance

import datetime

cet = datetime.timezone(datetime.timedelta(hours=2), name="CET")
time = datetime.time(12, 33, 45, 234154, cet)
print("Time:", time)
print("Timezone:", time.tzname())
time = time.replace(tzinfo=None)
print("Changed Timezone:", time)
print("Timezone:", time.tzname())

Output:

Time: 12:33:45.234154+02:00
Timezone: CET
Changed Timezone: 12:33:45.234154
Timezone: None
  1. The Python code above first creates a timezone for CET or Central European Time which is +02:00.

  2. Next, using the datetime.time() constructor, we create a time object and set the timezone to CET. The tzname() method confirms that.

  3. Now, using the replace() method, we set the timezone of the time object to None. This operation converts a timezone-aware time object to a naive object.

  4. From the output, we can understand that the time values did not revert to UTC-based values; only the timezone changed. We can verify that by using the tzname() method.

    The timezone name is printed as None, indicating no timezone is present. Moreover, we can confirm that from the output.

    The updated time object doesn’t have a ±HH:MM value at the end of it (12:33:45.234154), unlike the original object where the value is +02:00 (12:33:45.234154+02:00), signaling that there is no timezone.

Note that the tzname() method sometimes raises an exception if it fails to find a string name for the timezone. To bypass that, we can use try-except blocks and catch the exception.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Datetime