3982

How do I get the current time in Python?

2
  • 85
    please note, the most voted answers are for timezonoe-naive datetime, while we see that in production environment more and more services across the world are connected together and timezone-aware datetime become the required standard Commented Apr 29, 2020 at 17:12
  • 6
    This is a very valid point by @SławomirLenart and here is a quick tutorial showing multiple ways to get the current time based on the timezone Commented Aug 14, 2021 at 14:26

54 Answers 54

1
2
13

You can do so using ctime():

from time import time, ctime t = time() ctime(t) 

output:

Sat Sep 14 21:27:08 2019

These outputs are different because the timestamp returned by ctime() depends on your geographical location.

Sign up to request clarification or add additional context in comments.

Comments

13

Method1: Getting Current Date and Time from system datetime

The datetime module supplies classes for manipulating dates and times.

Code

from datetime import datetime,date print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day)) print("Year: "+str(date.today().year)) print("Month: "+str(date.today().month)) print("Day: "+str(date.today().day)+"\n") print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second)) print("Hour: "+str(datetime.today().hour)) print("Minute: "+str(datetime.today().minute)) print("Second: "+str(datetime.today().second)) print("MilliSecond: "+str(datetime.today().microsecond)) 

Output will be like

Date: 2020-4-18 Year: 2020 Month: 4 Day: 18 Time: 19:30:5 Hour: 19 Minute: 30 Second: 5 MilliSecond: 836071 

Method2: Getting Current Date and Time if Network is available

urllib package helps us to handle the url's that means webpages. Here we collects data from the webpage http://just-the-time.appspot.com/ and parses dateime from the webpage using the package dateparser.

Code

from urllib.request import urlopen import dateparser time_url = urlopen(u'http://just-the-time.appspot.com/') datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1] date = datetime[0] time = datetime[1] print("Date: "+str(date)) print("Year: "+str(date.split('-')[0])) print("Month: "+str(date.split('-')[1])) print("Day: "+str(date.split('-')[2])+'\n') print("Time: "+str(time)) print("Hour: "+str(time.split(':')[0])) print("Minute: "+str(time.split(':')[1])) print("Second: "+str(time.split(':')[2])) 

Output will be like

Date: 2020-04-18 Year: 2020 Month: 04 Day: 18 Time: 14:17:10 Hour: 14 Minute: 17 Second: 10 

Method3: Getting Current Date and Time from Local Time of the Machine

Python's time module provides a function for getting local time from the number of seconds elapsed since the epoch called localtime(). ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.

Code

from time import time, ctime datetime = ctime(time()).split(' ') print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2])) print("Year: "+str(datetime[4])) print("Month: "+str(datetime[1])) print("Day: "+str(datetime[2])) print("Week Day: "+str(datetime[0])+'\n') print("Time: "+str(datetime[3])) print("Hour: "+str(datetime[3]).split(':')[0]) print("Minute: "+str(datetime[3]).split(':')[1]) print("Second: "+str(datetime[3]).split(':')[2]) 

Output will be like

Date: 2020-Apr-18 Year: 2020 Month: Apr Day: 18 Week Day: Sat Time: 19:30:20 Hour: 19 Minute: 30 Second: 20 

Comments

11

try this one:-

from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) 

Comments

10
import datetime date_time = str(datetime.datetime.now()).split() date,time = date_time 

date will print date and time will print time.

Comments

9

The following is what I use to get the time without having to format. Some people don't like the split method, but it is useful here:

from time import ctime print ctime().split()[3] 

It will print in HH:MM:SS format.

Comments

9

This question is for Python but since Django is one of the most widely used frameworks for Python, its important to note that if you are using Django you can always use timezone.now() instead of datetime.datetime.now(). The former is timezone 'aware' while the latter is not.

See this SO answer and the Django doc for details and rationale behind timezone.now().

from django.utils import timezone now = timezone.now() 

Comments

8

This is so simple. Try:

import datetime date_time = str(datetime.datetime.now()) date = date_time.split()[0] time = date_time.split()[1] 

Comments

7
from time import ctime // Day {Mon,Tue,..} print ctime().split()[0] // Month {Jan, Feb,..} print ctime().split()[1] // Date {1,2,..} print ctime().split()[2] // HH:MM:SS print ctime().split()[3] // Year {2018,..} print ctime().split()[4] 

When you call ctime() it will convert seconds to string in format 'Day Month Date HH:MM:SS Year' (for example: 'Wed January 17 16:53:22 2018'), then you call split() method that will make a list from your string ['Wed','Jan','17','16:56:45','2018'] (default delimeter is space).

Brackets are used to 'select' wanted argument in list.

One should call just one code line. One should not call them like I did, that was just an example, because in some cases you will get different values, rare but not impossible cases.

2 Comments

You might also want to explain why extracting parts from multiple calls of ctime() like that (using "current" time at each call) will not necessarily give a useful value in combination with each other.
What is // doing here?
7

Get current date time attributes:

import datetime currentDT = datetime.datetime.now() print ("Current Year is: %d" % currentDT.year) print ("Current Month is: %d" % currentDT.month) print ("Current Day is: %d" % currentDT.day) print ("Current Hour is: %d" % currentDT.hour) print ("Current Minute is: %d" % currentDT.minute) print ("Current Second is: %d" % currentDT.second) print ("Current Microsecond is: %d" % currentDT.microsecond) #!/usr/bin/python import time; ticks = time.time() print "Number of ticks since "12:00am, Jan 1, 1970":", ticks 

Comments

5

First import the datetime module from datetime

from datetime import datetime 

Then print the current time as 'yyyy-mm-dd hh:mm:ss'

print(str(datetime.now()) 

To get only the time in the form 'hh:mm:ss' where ss stands for the full number of seconds plus the fraction of seconds elapsed, just do;

print(str(datetime.now()[11:]) 

Converting the datetime.now() to a string yields an answer that is in the format that feels like the regular DATES AND TIMES we are used to.

Comments

5

If you using it for django datetime sometimes won't work on server so I recommend using timezone

But for use django timezone you should set your country timezone code in your settings.py

TIME_ZONE = 'Asia/Tashkent' 

Then you can use it

from django.utils import timezone timezone.now() // for date time timezone.now().year // for yaer timezone.now().month // for month timezone.now().day // for day timezone.now().date // for date timezone.now().hour // for hour timezone.now().weekday // for minute 

or if you want use on python

import time time.strftime('%X') // '13:12:47' time.strftime('%x') // '01/20/22' time.strftime('%d') // '20' day time.strftime('%m') // '01' month time.strftime('%y') // '20' year time.strftime('%H') // '01' hour time.strftime('%M') // '01' minute time.strftime('%m') // '01' second 

2 Comments

Your example may cause bad programming. strftime() or now() should never be used multiple times. If you use that method at 23:59:59 your result may mix data from 2 different days.
Thanks for your attention, but the question is not about using multiple times it's about getting the time. here I showed how to get not only time others too.
4

The time module can import all sorts of time stuff, inculduing sleep and other types of stuff including - the current time type

import time time.strftime("%T", time.localtime()) 

The output should look like this

05:46:33 11:22:56 13:44:55 22:33:44 00:00:00 

Comments

4

we can accomplish that Using datetime module

>>> from datetime import datetime >>> now = datetime.now() #get a datetime object containing current date and time >>> current_time = now.strftime("%H:%M:%S") #created a string representing current time >>> print("Current Time =", current_time) Current Time = 17:56:54 

In addition, we can get the current time of time zome using pytZ module.

>>> from pytz import timezone >>> import pytz >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> amsterdam = timezone('Europe/Amsterdam') >>> datetime_eu = datetime.now(amsterdam) >>> print("Europe time::", datetime_eu.strftime("%H:%M:%S")) Europe time:: 14:45:31 

Comments

4

From Python 3.9, the zoneinfo module can be used for getting timezones rather than using a third party library.

To get the current time in a particular timezone:

from datetime import datetime from zoneinfo import ZoneInfo datetime.now(tz=ZoneInfo("Europe/Amsterdam")) 

2 Comments

The latest version of Python available for download is 3.8.5! python.org/downloads
Sure, but in the future, when other people are reading this, that won't be the case. In fact, the first release candidate was released today: docs.python.org/3.9/whatsnew/3.9.html
4

If you use pandas a lot you can use Timestamp, which is the equivalent of Python’s Datetime:

In [1]: import pandas as pd In [2]: pd.Timestamp.now() Out[2]: Timestamp('2022-06-21 21:52:50.568788') 

And just the time:

In [3]: pd.Timestamp.now().strftime("%H:%M:%S") Out[3]: '21:53:01' 

2 Comments

Solution is valid, but it is an overkill to have pandas dependency just for getting current time.
Yeah, it's meant for people who use pandas on a daily basis and therefore already imported the library.
4
import datetime print('date='+datetime.datetime.now().__str__().split(' ')[0]+' '+'time='+datetime.datetime.now().__str__().split(' ')[1] 

Since Qt is used extensively,

from PyQt5 import QDateTime print(QDateTime.currentDateTime().__str__().split('(')[1].rstrip(')')) 

2 Comments

Compared to the other answers, yours is quit long and complex
@Molitoris, it is advised to (re)use the functions available from already imported libraries. So, this is useful for those who are already working on Qt-Python.
3

There are so many complex solutions here it could be confusing for a beginner. I find this is the most simple solution to the question - as it just returns the current time as asked (no frills):

import datetime time_now = datetime.datetime.now() display_time = time_now.strftime("%H:%M") print(display_time) 

If you wanted more detail back than just the current time, you can do what some others have suggested here:

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

Although this approach is shorter to write, it returns the current date and milliseconds as well, which may not be required when simply looking to return the current time.

Comments

2

If you want the time for purpose of timing function calls, then you want time.perf_counter().

start_time = time.perf_counter() expensive_function() time_taken = time.perf_counter() - start_time print(f'expensive_function() took {round(time_taken,2)}s') 

time.perf_counter() → float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.


time.perf_counter_ns() → int

Similar to perf_counter(), but return time as nanoseconds.

New in version 3.7.

Comments

1

Attributes of now() can be used to get the current time in python:

# importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print ("The attributes of now() are : ") print ("Year : ", end = "") print (current_time.year) print ("Month : ", end = "") print (current_time.month) print ("Day : ", end = "") print (current_time.day) print ("Hour : ", end = "") print (current_time.hour) print ("Minute : ", end = "") print (current_time.minute) print ("Second : ", end = "") print (current_time.second) print ("Microsecond : ", end = "") print (current_time.microsecond) 

Comments

0

Here's the code which will only show time according to your question:

 from datetime import datetime time= datetime.now() b = time.strftime("%H:%M:%S") print(b) 
  • Used datetime.now() to get the current date and time.
  • Then used .strftime to get desired value i.e time only.

strftime is used to retrieve the desired output or to change the default format according to our need.

Comments

-1

Use this method for UTC DateTime, local Date-Time, and convert am and pm

import pytz from datetime import datetime #UTC Time print("UTC Date and time") epoch: datetime =datetime.now().replace(tzinfo=pytz.utc) print(epoch) #local date and time print("Local Date and time") today = datetime.now() local_time = today.strftime("%Y-%M-%d:%H:%M:%S") print(local_time) #convert time to AM PM format print("Date and time AM and PM") now = today.strftime("%Y-%M-%d:%I:%M %p") print(now) 

1 Comment

Downvote for using the deprecated pytz, compounded by the fact that there also is a datetime.timezone.utc.
-1

Gets the current time and converts it to string:

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

Comments

-1
import datetime import pytz # for timezone() import time current_time1 = datetime.datetime.now() current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei')) current_time3 = datetime.datetime.utcnow() current_time4 = datetime.datetime.now().isoformat() current_time5 = time.gmtime(time.time()) print("datetime.datetime.now():", current_time1) print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2) print("datetime.utcnow():", current_time3) print("datetime.datetime.now().isoformat():", current_time4) print('time.gmtime(time.time()): ', current_time5) 

1 Comment

There are, already, 52 other answers posted. How would your code block with no commentary contribute something new to the discussion?
-1

If you need a time-zone aware solution. I like to use the following 5 lines of code to get the current time.

from datetime import datetime import pytz # Specify the timezone my_time_zone = pytz.timezone('Asia/Singapore') # Pass the timezone to datetime.now() function my_time = datetime.now(my_time_zone) # Convert the type `my_time` to string with '%Y-%m-%d %H:%M:%S' format. current_time = my_time.strftime('%Y-%m-%d %H:%M:%S') # current_time would be something like 2023-01-23 14:09:48 

You can find the list of all timezones using pytz.all_timezones.

The meaning of the symbols in %Y-%m-%d %H:%M:%S can be found in geeksforgeeks Python strftime() function

1 Comment

Btw. we have time zone handling in the standard library, see zoneinfo.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.