Python datetime – Getting the current date and time

In this tutorial we will be retrieving the current date and time using a Python script. To do this we will be using the ‘datetime’ module which supplies classes for manipulating dates and times.

The code below shows us how to retrieve and print both the date and time.

import datetime

now = datetime.datetime.now()
print(now)

If we are wanting to print just the date alone we’d adjust the code to the below.

import datetime

now = datetime.datetime.now()
date = now.date()

print(date)

similarly we can print just the time alone via the below.

import datetime

now = datetime.datetime.now()
time = now.time()

print(time)

Leave a Reply