Python datetime.datetime() Class
-
Syntax of Python
datetime.datetime()
Class -
Example 1: Use the
datetime.datetime()
Class in Python -
Example 2: Enter Out of Range Values in
datetime.datetime()
Class -
Example 3: Display Some Arguments of the
datetime.datetime()
Class
Python datetime.datetime()
class is an efficient way of handling time and date in Python simultaneously. When an object of the datetime.datetime()
class is instantiated, it represents a date and time in a specified format.
Syntax of Python datetime.datetime()
Class
datetime.datetime(year, month, day)
datetime.datetime(year, month, day, hour, minute, second, microsecond, tzinfo)
Parameters
year |
The year should be in the range: MINYEAR <= year <= MAXYEAR . |
month |
It is an integer in the range: 1 <= month <= 12 . |
day |
It is an integer in the range: 1 <= day <= number of days in the given month and year . |
hour |
(optional) It is an integer in the range: 0 <= hour < 24 . |
minute |
(optional) It is an integer in the range: 0 <= minute < 60 . |
second |
(optional) It is an integer in the range: 0 <= second < 60 . |
microsecond |
(optional) It is an integer in the range: 0 <= microsecond < 1000000 . |
tzinfo |
(optional) By default it is set to None . It is an instance of a tzinfo subclass. |
Return
This class does not return a value.
Example 1: Use the datetime.datetime()
Class in Python
import datetime
datetime_object = datetime.datetime(2022, 8, 29, 12, 3, 30)
print("The date and time entered are: ", datetime_object)
Output:
The date and time entered are: 2022-08-29 12:03:30
The above code shows only the attributes which we have specified.
Example 2: Enter Out of Range Values in datetime.datetime()
Class
import datetime
datetime_object = datetime.datetime(0, 0, 0, 0, 0, 0)
print("The date and time entered are: ", datetime_object)
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
datetime_object = datetime.datetime(0,0,0,0,0,0)
ValueError: year 0 is out of range
The year, month, and date can never be 0. So, any argument entered outside the results of the above-specified range in a ValueError
exception.
Example 3: Display Some Arguments of the datetime.datetime()
Class
import datetime
datetime_object = datetime.datetime(2022, 8, 29, 23, 55, 59, 342380)
print("year =", datetime_object.year)
print("month =", datetime_object.month)
print("hour =", datetime_object.hour)
print("minute =", datetime_object.minute)
Output:
year = 2022
month = 8
hour = 23
minute = 55
We can use the .
dot notation to access specific parts of the datetime
object.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn