Press "Enter" to skip to content

Get current time in Python

To get the current time in python there are various ways. We will discuss about getting time using datetime, and timezone.

The general idea is to get the system time, format it and print. Let’s look at some of the examples.

Get current time using datetime in python

from datetime import datetime

# Get the date and time
date_with_time = datetime.now()
print("Date and time is : ", date_with_time)

#We want only time part, so get the time
only_time = date_with_time.strftime("%H : %M : %S")
print("Current Time is : ", only_time)

Output

Date and time is :  2021-06-05 07:31:32.495159
Current Time is :  07 : 31 : 32
Freshers Placement

The above program used datetime.now() to get the current date and time. But we want only current time, so we used strftime().

To extract hours use %H, for minutes use %M, and for seconds use %S.

Get time without using strftime()

from datetime import datetime

#Only time part without date
current_time = datetime.now().time()

print("Current time : ", current_time)

Output

Current time :  07:40:33.005999

In the above program we directly got the time part without using strftime().

Time module example

If you don’t want to use datetime, then you can go ahead with time module. Let’s look at the example of how to use time module to extract current time.

import time

#Local time has date and time
local_time = time.localtime()
print('Local Time is ', local_time)

# Extract the time part
current_time = time.strftime("%H:%M:%S", local_time)
print('Current time is ', current_time)
Freshers Placement

Output

Local Time is  time.struct_time(tm_year=2021, tm_mon=6, tm_mday=5, tm_hour=7, tm_min=50, tm_sec=4, tm_wday=5, tm_yday=156, tm_isdst=0)
Current time is  07:50:04

time.localtime() returns the struct that has date and time.

Get current time for a specific time zone

from datetime import datetime
import pytz

timezone_costa_rica = pytz.timezone('America/Costa_Rica') 
costa_rica = datetime.now(timezone_costa_rica)
print("Costa_Rica time:", costa_rica.strftime("%H:%M:%S"))

Output

Costa_Rica time: 01:58:04

As we saw, we can get the current time for a timezone. In our example we got it for costa rica, but you can get it for any timezone.

To get the list of complete timezones, you can run following program.

print(pytz.all_timezones)
Freshers Placement

This program returns all available time zones.

Get GMT time

To get the GMT use gmtime()

from time import gmtime, strftime
# gmtime returns GMT time
print('Current GMT time is',strftime("%H:%M:%S", gmtime()))

Output

Current GMT time is 08:12:50

Comments are closed.