Python datetime timetz() Method with Example

Python datetime.timetz() Method: In this tutorial, we will learn about the timetz() method of datetime class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python datetime.timetz() Method

The datetime.timetz() method is used to convert and get a time object of an instance of datetime object with the same hour, minute, second, microsecond, fold, and tzinfo attributes. Like datetime.time() method the tzinfo is not None here if present in the original datetime instance object.

Module

The following module is required to use timetz() method:

import datetime

Class

The following class is required to use timetz() method:

from datetime import datetime

Syntax

The following is the syntax of timetz() method:

timetz()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a time object with same hour, minute, second, microsecond, fold and tzinfo.

Example of datetime timetz() Method in Python

## Creating a time object from a datetime object
import datetime
## Creating datetime instance
x = datetime.datetime(2020, 3, 4, 23, 12, 23, 44)
d = x.timetz()
print("Original object:", x)
print("New time object:",d)
print()

x = datetime.datetime.now()
d = x.timetz()
print("Original date and time", x)
print("New time object:", d)
print()

t = datetime.timedelta(hours=5, minutes= 30)
tzobj = datetime.timezone(t, name="IST")
x = datetime.datetime(2020, 3, 22, 12, 23, 34, 45, tzobj)
d = x.timetz()
print("Original datetime object:", x)
print("Time object with tzinfo attributes:", d)
print("Time object without tzinfo attributes:", x.time())

Output

Original object: 2020-03-04 23:12:23.000044
New time object: 23:12:23.000044

Original date and time 2020-05-03 18:26:35.437067
New time object: 18:26:35.437067

Original datetime object: 2020-03-22 12:23:34.000045+05:30
Time object with tzinfo attributes: 12:23:34.000045+05:30
Time object without tzinfo attributes: 12:23:34.000045



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.