API · Python

Python datetime.datetime.now() Method

The datetime.datetime.now() is an in-built Python function used to find the current time.

On this page

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

Syntax of Python datetime.datetime.now() Method

datetime.datetime.now(time_zone)
datetime.datetime.now()

Parameter

time_zone optional By default, this parameter is set to None. We enter the time zone in which we want the current time to be converted.

Return

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

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

import datetime

time = datetime.datetime.now()

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

Output:

The time in this instance is: 2022-08-26 16:55:45.793722

The above code shows the current time of the system.

Example Codes: Convert the Time Into Another Time Zone With the datetime.datetime.now() Method

import datetime

time = datetime.datetime.now(datetime.timezone.utc)

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

Output:

The time in this instance is: 2022-08-26 17:07:55.869159+00:00

If we specify the time zone as a parameter to this method, the compiler automatically converts the system time into the desired time zone.

Example Codes: Find the Time Zone With the datetime.datetime.now() Method

import datetime

time = datetime.datetime.now(datetime.timezone.utc).astimezone().tzname()

print("Current time zone: ", time)

Output:

Current time zone:  Pakistan Standard Time

The time returned by this method is in the time zone the system is currently using.

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

import datetime

time = datetime.datetime.now()

print("The attributes of `datetime.datetime.now()` 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.now()` 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 easily. 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.