How do I get the current time in Python?
- 85please 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 standardSławomir Lenart– Sławomir Lenart2020-04-29 17:12:44 +00:00Commented Apr 29, 2020 at 17:12
- 6This 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 timezoneHitesh Garg– Hitesh Garg2021-08-14 14:26:31 +00:00Commented Aug 14, 2021 at 14:26
54 Answers
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
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
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
ctime() like that (using "current" time at each call) will not necessarily give a useful value in combination with each other.// doing here?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
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
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
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
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
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
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
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
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
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
.strftimeto 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
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
datetime.timezone.utc.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
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