Python DateTime now()

Python DateTime now() Function

datetime.datetime.now() function returns datetime object containing current date and time of the system during the execution of now() statement.

In this tutorial, we will learn the syntax of datetime now() function and use it in some example Python programs to understand its usage.

Syntax – datetime.now()

The syntax of now() function is given below.

now(tz=None)
Run this program

where tz is TimeZone and by default None.

Example 1: DateTime now()

In the following program, we shall use now() function to get current date and time, convert it to string and print to console.

Python Program

from datetime import datetime

datetime_1 = datetime.now()
print(str(datetime_1))
Run this program

Output

2020-06-21 12:32:48.066025

Example 2: DateTime now() – With TimeZone Argument

In the following program, let us pass timezone argument to now() function and get the current date and time specific to the timezone.

Python Program

from datetime import datetime
import pytz

tz = pytz.timezone('US/Pacific')
datetime_1 = datetime.now(tz)
print(str(datetime_1))
Run this program

Output

2020-06-21 00:09:08.130167-07:00

Summary

Summarizing this Python Tutorial, we learned how to use DateTime now() function, to get the current date and time of your current timezone, or a specific timezone.