×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python datetime time() Method with Example

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

Python datetime.time() Method

The datetime.time() method is used to convert and return a time object of an instance of datetime object with the same hour, minute, second, microsecond, and fold.

Module

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

import datetime

Class

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

from datetime import datetime

Syntax

The following is the syntax of time() method:

time()

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 and fold. tzinfo is None.

Example of datetime time() Method in Python

## Creating a time object from a datetime object
from datetime import datetime
import pytz

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

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

x = datetime.today()
d = x.time()
print("Printing the same")
print(x)
print(d)
print()

t = pytz.timezone("Asia/Kolkata")
## Adding tzinfo
x = x.astimezone(t)
d = x.time()
## Note: tzinfo is also not added in the object
## therefor giving a naive time object
print(x)
print(d)

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:05:23.458667
New time objec: 18:05:23.458667

Printing the same
2020-05-03 18:05:23.458730
18:05:23.458730

2020-05-03 23:35:23.458730+05:30
23:35:23.458730

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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