The Wayback Machine - https://web.archive.org/web/20240710005334/https://www.geeksforgeeks.org/python-datetime-time-class/
Open In App

Python DateTime – Time Class

Last Updated : 03 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Time class represents the local time of the day which is independent of any particular day. This class can have the tzinfo object which represents the timezone of the given time. If the tzinfo is None then the time object is the naive object otherwise it is the aware object.

Syntax:

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the following range –

  • 0 <= hour < 24
  • 0 <= minute < 60
  • 0 <= second < 60
  • 0 <= microsecond < 1000000
  • fold in [0, 1]

Example:

Python3




# Python program to
# demonstrate time class
 
from datetime import time
 
# calling the constructor
my_time = time(12, 14, 36)
 
print("Entered time", my_time)
 
# calling constructor with 1
# argument
my_time = time(minute = 12)
print("\nTime with one argument", my_time)
 
# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)
 
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
 
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int


Output

Entered time 12:14:36

Time with one argument 00:12:00

Time without argument 00:00:00

Class Attributes

Let’s see the attributes provided by this class – 

Attribute Name Description
min Minimum possible representation of time
max Maximum possible representation of time
resolution The minimum possible difference between time objects
hour The range of hour must be between 0 and 24 (not including 24)
minute The range of minute must be between 0 and 60 (not including 60)
second The range of second must be between 0 and 60 (not including 60)
microsecond The range of microsecond must be between 0 and 1000000 (not including 1000000)
tzinfo The object containing timezone information
fold Represents if the fold has occurred in the time or not

Example 1: Getting min and max representable time

Python3




from datetime import time
 
# Getting min time
mintime = time.min
print("Min Time supported", mintime)
 
# Getting max time
maxtime = time.max
print("Max Time supported", maxtime)


Output

Min Time supported 00:00:00
Max Time supported 23:59:59.999999

Example 2: Accessing the hour, minutes, seconds, and microseconds attribute from the time class 

Python3




from datetime import time
 
# Creating Time object
Time = time(12,24,36,1212)
 
# Accessing Attributes
print("Hour:", Time.hour)
print("Minutes:", Time.minute)
print("Seconds:", Time.second)
print("Microseconds:", Time.microsecond)


Output

Hour: 12
Minutes: 24
Seconds: 36
Microseconds: 1212

Class Functions

Time class provides various functions like we can get time from string or convert time to string, format the time according to our need, etc. Let’s see a list of all the functions provided by the time class. 

List of Time Class Functions

Function Name Description
dst() Returns tzinfo.dst() is tzinfo is not None
fromisoformat() Returns a time object from the string representation of the time
isoformat() Returns the string representation of time from the time object
replace() Changes the value of the time object with the given parameter
strftime() Returns a string representation of the time with the given format
tzname() Returns tzinfo.tzname() is tzinfo is not None
utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

Let’s see certain examples of the above functions

Example 1: Converting time object to string and vice versa 

Python3




from datetime import time
 
# Creating Time object
Time = time(12,24,36,1212)
 
# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))
 
Time = "12:24:36.001212"
 
# Converting string to Time object
Time = time.fromisoformat(Str)
print("\nTime from String", Time)
print(type(Time))


Output 

String Representation: 12:24:36.001212
<class 'str'>

Time from String 12:24:36.001212
<class 'datetime.time'>

Example 2: Changing the value of an already created time object and formatting the time 

Python3




from datetime import time
 
# Creating Time object
Time = time(12,24,36,1212)
print("Original time:", Time)
 
# Replacing hour
Time = Time.replace(hour = 13, second = 12)
print("New Time:", Time)
 
# Formatting Time
Ftime = Time.strftime("%I:%M %p")
print("Formatted time", Ftime)


Output

Original time: 12:24:36.001212
New Time: 13:24:12.001212
Formatted time 01:24 PM

Note: For more information on Python Datetime, refer to Python Datetime Tutorial

 



Previous Article
Next Article

Similar Reads

Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Manipulate Date and Time with the Datetime Module in Python
Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python's standard utility modules we can easily manipulate date and time according to our own need
9 min read
Python DateTime - time.replace() Method with Example
In this article, we will discuss the time.replace() method in Python. This method is used to manipulate objects of time class of module datetime. It is used to replace the time with the same value, except for those parameters given new values by whichever keyword arguments. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters:
2 min read
Extract time from datetime in Python
In this article, we are going to see how to extract time from DateTime in Python. In Python, there is no such type of datatype as DateTime, first, we have to create our data into DateTime format and then we will convert our DateTime data into time. A Python module is used to convert the data into DateTime format, but in the article, we will be usin
4 min read
How to add time onto a DateTime object in Python
In this article, we will discuss the addition of time onto a specified DateTime object in Python. The effect of this will produce a new DateTime object. This addition can be performed by using datetime.timedelta() function. The timedelta() function is used for calculating differences in dates and also can be used for date manipulations in Python. I
2 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
isocalendar() Function Of Datetime.date Class In Python
The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 full weeks.ISO years do not have any fractional weeks
2 min read
fromtimestamp() Function Of Datetime.date Class In Python
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method. Syntax: @classmethod fromtimestamp(timestamp) Parameters: This fun
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg