Syntax of Python DateTime
The syntax of the Python DateTime class is as follows:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
The year, month, and day arguments are mandatory. The tzinfo can be None, and the rest all the attributes must be an integer in the following range:
- MINYEAR(1) <= year <= MAXYEAR(9999)
- 1 <= month <= 12
- 1 <= day <= number of days in the given month and year
- 0 <= hour < 24
- 0 <= minute < 60
- 0 <= second < 60
- 0 <= microsecond < 1000000
- fold in [0, 1]
Note: Passing an argument other than an integer will raise a TypeError and passing arguments outside the range will raise ValueError.
Example: Creating an instance of the DateTime class
Python3
# Python program to # demonstrate datetime object from datetime import datetime # Initializing constructor a = datetime( 2022 , 10 , 22 ) print (a) # Initializing constructor # with time parameters as well a = datetime( 2022 , 10 , 22 , 6 , 2 , 32 , 5456 ) print (a) |
Output:
2022-10-22 00:00:00
2022-10-22 06:02:32.005456
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 class are potentially aware objects i.e. it contains information regarding time zone as well.