How to Get the Current Date and Time in Python?

Spread the love

Problem –

You want to get the current date and time in python.

Solution –

To get the current date and time in python, you can use the datetime module.

In [1]: from datetime import datetime

In [2]: now = datetime.now()

In [3]: now
Out[3]: datetime.datetime(2022, 6, 21, 8, 25, 11, 35507)

In [4]: print(now)
2022-06-21 08:25:11.035507

To only get the time without the date.


In [5]: now.time()
Out[5]: datetime.time(8, 25, 11, 35507)

In [6]: print(now.time())
08:25:11.035507

And if you only want the date without the time.

In [7]: now.date()
Out[7]: datetime.date(2022, 6, 21)

In [8]: print(now.date())
2022-06-21

Rating: 1 out of 5.

Leave a Reply