close

How to get the current time in Python

In Python, We Need Sometime Current Time in Our Python Project. So Today We are going to learn How to get the current time in Python? Let’s get started with this tutorial.

How to get the current time in Python?

Basically Here I am we will interact with three methods In which First One is Using DateTime Second is Using time.strftime() and the Third is Using datetime and strftime together so let’s Get Start All Three methods without Wasting Your Time.

  1. How to get the current time in Python

    To get the current time in Python Package DateTime is Providing current time So In Method 1 We are going to import DateTime in Our Code and We will retrieve the current time with it. Just Write datetime.datetime.now() and You will Get the Current time in output.

  2. get the current time in Python

    To get the current time in Python In Method 2 We are going to Use time.strftime() First of all you need to import strftime from time and then Just Add DateTime formate in strftime() and It will give you output as your preferred time. InShort Whatever Formate You need You can Simply Pass It In Your strftime and you will get desired DateTime formate that you need.

Method 1: Using datetime

Package DateTime is Providing current time So In Method 1 We are going to import DateTime in Our Code and We will retrieve the current time with it. Here is my first Example.

import datetime
timeNow = datetime.datetime.now()
print(timeNow )

And Output Of My Above Code Will be

2021-02-18 12:57:35.74120

Just Write datetime.datetime.now() and You will Get the Current time in output.

Method 2: Use time.strftime()

In Method 2 We are going to Use time.strftime() First of all you need to import strftime from time and then Just Add DateTime formate in strftime() and It will give you output as your preferred time. Here is My example.

Get Current Datetime in YY-MM-DD HH:MM:SS Formate

from time import gmtime, strftime
print(strftime("%Y-%m-%d %H:%M:%S"))

OutPut

2022-02-18 09:32:59

Get Current Datetime in YY-MM-DD Formate

from time import gmtime, strftime
print(strftime("%Y-%m-%d"))

OutPut

2022-02-18

InShort Whatever Formate You need You can Simply Pass It In Your strftime and you will get desired DateTime formate that you need.

Suppose If You Want Only Today Date, Month And Year Then You Can Pass Y-M-D in strftime Just Like this.

strftime("%Y-%M-%D")

Method 3: Using datetime and strftime together

You Can also Use datetime and strftime together. Here is My example.

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

OutPut

2022-02-18 09:38:31

So This is How You Can Get Current DateTime Using DateTime and strftime together

Conclusion

Hope all 3 Method Are Useful For You. Comment Below Which Method You Used To Retrieve the current time in Python. Thank You.

Leave a Comment