How the datetime() class works in Python
Datetime module in Python
Date and Time in Python are not a datatypes on their own, but we can import a datetime module. The datetime module in Python helps in providing six different classes for making use of dates and times in different formats in many different applications. These classes are date, time, datetime, timedelta, tzinfo, timezone.
In this shot, we’ll learn about the datetime class from the datetime module.
The datetime class
The datetime class provides information on the date and the time. It assumes the current Gregorian calendar to be extended in both directions and also assumes that there are exactly
3600 * 24 = 86400 seconds in a day.
Syntax
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Parameters
The function arguments year, month, and day, are necessary. The tzinfo parameter can be set to None. All the remaining values must be an integer in ranges defined below:
Attribute | Range |
year | MINYEAR < and <= MAXYEAR |
month | 1 <= and <= 12 |
day | 1 <= and <= number of days in the given month and year |
hour | 0 <= and < 24 |
minute | 0 <= and < 60 |
second | 0 <= and < 60 |
microsecond | 0 <= and < 1000000 |
fold | [0, 1] |
Return value
It returns the date type object.
If we pass any argument other than an integer, we’ll get a TypeError exception. If the given arguments exceed the upper boundary, we’ll get the ValueError exception.
Example
from datetime import datetimedate = datetime(10_000, 1, 1)print(f'The event started on {date:%B, %d %Y}')
Explanation
- Line 1: We import the library,
datetime. - Line 3: We call the
datetimemethod withyear,month, anddayas arguments. It returns the value stored in theresultvariable. - Line 4: We print the
datevalue.
The value must be between maximum and minimum value.
from datetime import datetimeprint(datetime.min, datetime.max)
The value provided in the teaser is bigger than the maximum value for datetime. Hence, the ValueError exception.
The now() method
In the code given below, we use the now() method and provide the current local date and time.
Example
from datetime import datetimedatetime = datetime.now()print("Year: ", datetime.year)print("Month: ", datetime.month)print("Date: ", datetime.day)print("Hour: ", datetime.hour)print("Minute: ", datetime.minute)print("Second: ", datetime.second)print("TimeZone info: ", datetime.tzinfo)
Explanation
- Line 1: We import the library,
datetime. - Line 3: We call the
datetime.now()method and store the output in thedatetimevariable. - Lines 5–11: We print the
datetimevalue.
The strftime() method
We can also convert date objects into strings using the strftime() method.
Example
from datetime import datetimestr_date = datetime(2022, 9, 5)print(str_date.strftime("%B"))
Explanation
- Line 1: We import the library,
datetime. - Line 3: We call the
datetimemethod withyear,month, anddayas arguments. It returns the value stored in thestr_datevariable. - Line 4: We call the
strtime()method withstr_dateand print it.
Important functions of datetime class
Function name | Description |
fromisoformat() | It returns a datetime object according to string representation. |
utcnow() | It returns the current UTC date and time |
timetuple() | It returns an object of the type `time.struct_time` |
today() | It returns local DateTime and tzinfo as None in it. |
replace() | It changes the specified attributes of given the DateTime object |
astimezone() | It returns the timezone information of DateTime object. |
strptime() | It returns a DateTime object relevant to the date string |
tzname() | It returns the name of the relevant timezone |
Free Resources