How to get the current date and time in Python

We can use datetime module to get the date and time in Python.

from datetime import date
today = date.today()
print("Today's date:", today)

This can be converted to any format using strftime utility.

Let's discuss with examples.

dd/mm/YY

d = today.strftime("%d/%m/%Y")
print (d)

Textual month, day and year

d = today.strftime("%B %d, %Y")
print (d)

mm/dd/y

d = today.strftime("%m/%d/%y")
print (d)

Month abbreviation, day and year

d = today.strftime("%b-%d-%Y")

If we require time along with the date, datetime utility can be used.

now = datetime.now()
print(now)

This also can be format using strftime utility.

For converting to dd/mm/YY H:M:S format,

d = now.strftime("%d/%m/%Y %H:%M:%S")
print(d)

That's all…

Leave a Reply

Your email address will not be published. Required fields are marked *