Hit enter after type your search item

Getting current date by Python datetime now() function

In this tutorial, you are going to learn how to get the current date and time by now() function of Python datetime() module.

Later, you can also see the other ways of getting the current time.

How to use now() function?

The timedate now() function returns the current local date and time.

The general syntax for using the now() function is:


Where tz argument specifies the time zone. If a value of None is given, this is like today(). For other than None value, it must be an instance of the tzinfo subclass. You may learn more about tzinfo subclass here.

An example of Python now() to get current local date and time

The following example displays the current local date and time by using the now() function of the datetime. For that, you first need to import datetime module, as shown in the example below:


“It should display the current date and time of the system”

The example of using time zone argument

This example uses the time zone argument in the datetime.now() function and displays the time in UTC (Universal Time Coordinated):

Getting date only by now() function

In the above examples, we get date and time as using the now() function. For only getting the current date, you may use the date() method as follows:

This should display the current date only.

How to get time only by now() function?

Similarly, by using the time() function, you may get the time only:

Only getting time in UTC time zone

The example below displays the time in UTC zone without date:

The example of getting date by using time module

You may use the time() module as well for getting the date and time for local time, GMT etc. The example below shows using the time module where I used strftime and localtime() functions for getting the local date and formatting as shown below:

The output of the above example should be current local time in this formation:

Tuesday, 14 Mar 2017

Getting GMT time using strftime and gmttime functions

Similarly, you may get the GMT time by using gmttime() function in the strftime() function as follows:

The output should be GMT time like this:

2018-12-04 09:41:09

You can see, this time we got the time as well as date. You may use the formatting directives as per the requirements.

You can see the list of directives here.

This div height required for enabling the sticky sidebar