Python Tutorial: datetime.datetime() class

The Pythondatetime.datetime() class is an efficient way to work with both time and date in Python. When an object of class datetime.datetime() is instantiated, it represents a date and time in the specified format.

Syntax for the datetime.datetime() class

datetime.datetime(year, month, day)
datetime.datetime(year, month, day, hour, minute, second, microsecond, tzinfo)

parameter

  • 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 value

This class does not return a value.

Example 1: Using 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 code above only displays the properties we specify.

Example 2: Entering an out-of-range value in the 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 result:

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

Year, month, and day can never be 0. Therefore, any parameter entered outside the range specified above results in a ValueError exception.

Example 3: Display some parameters of datetime.datetime() class

import datetime #Python小白学习交流群:711312441
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 a datetime object.

Guess you like

Origin blog.csdn.net/qdPython/article/details/131979761