Python datetime.datetime.today() Method

Musfirah Waseem Jan 30, 2023
  1. Syntax of Python datetime.datetime.today() Method
  2. Example Codes: Working With the datetime.datetime.today() Method
  3. Example Codes: Specify the Attributes to Be Shown by the datetime.datetime.today() Method
  4. Example Codes: Break Down the Attributes of the datetime.datetime.today() Method
Python datetime.datetime.today() Method

Python datetime.datetime.today() method is an efficient way of finding the current time on any platform.

Syntax of Python datetime.datetime.today() Method

datetime.datetime.today()

Parameters

No parameter is required.

Return

The return type of this method is an object containing the current date and time.

Example Codes: Working With the datetime.datetime.today() Method

import datetime

time = datetime.datetime.today()

print("The time in this instance is: ", time)

Output:

The time in this instance is: 2022-08-26 17:34:03.624886

The above code shows the current time of the system.

Example Codes: Specify the Attributes to Be Shown by the datetime.datetime.today() Method

import datetime

time = datetime.datetime.today().strftime("%Y-%m-%d")

print("Today's date is: ", time)

time = datetime.datetime.today().strftime("%H:%M:%S")

print("The current time is: ", time)

time = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")

print("Today's date and the current time are as follows: ", time)

Output:

Today's date is:  2022-08-26
The current time is:  17:42:41
Today's date and the current time are as follows:  2022-08-26 17:42:41

We can use the above code to represent the time and date in any format possible by the user.

Example Codes: Break Down the Attributes of the datetime.datetime.today() Method

import datetime

time = datetime.datetime.today()

print("The attributes of `datetime.datetime.today()` method are: ")

print("Year : ", end="")

print(time.year)

print("Month : ", end="")

print(time.month)

print("Day : ", end="")

print(time.day)

print("Hour : ", end="")

print(time.hour)

print("Minute : ", end="")

print(time.minute)

print("Second : ", end="")

print(time.second)

print("Microsecond : ", end="")

print(time.microsecond)

Output:

The attributes of `datetime.datetime.today()` method are:
Year : 2022
Month : 8
Day : 26
Hour : 17
Minute : 24
Second : 59
Microsecond : 184903

This method allows us to extract different attributes of date and time efficiently. This helps us to solve real-life applications easier, such as setting the alarm and checking if today’s date matches the set date or not.

Musfirah Waseem avatar Musfirah Waseem avatar

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

Related Article - Python DateTime