By user46646

2009-01-06 04:54:23 8 Comments

What is the module/method used to get the current time?


@Gad 2020-06-04 22:29:18

you can simply try the following

import datetime

now =

or use

import datetime

now =
print(now.strftime("%Y-%b-%d, %A %I:%M:%S$p")

@Tom Carrick 2020-06-27 10:10:32

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"Europe/Amsterdam"))

@Sandun 2020-08-22 13:49:15

The latest version of Python available for download is 3.8.5!

@Tom Carrick 2020-08-23 18:03:24

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:

@James McGuigan 2020-06-17 09:15:56

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

start_time = time.perf_counter()
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.

@Ransaka Ravihara 2020-06-13 12:49:31

we can accomplish that Using datetime module

>>> from datetime import 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')
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu =
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31

@Lucas Urban 2020-04-20 12:53:43

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


@Littin Rajan 2020-04-18 14:32:25

Method1: Getting Current Date and Time from system datetime

The datetime module supplies classes for manipulating dates and times.


from datetime import datetime,date

print("Date: "+str("-"+str("-"+str(
print("Year: "+str(
print("Month: "+str(
print("Day: "+str("\n")

print("Time: "+str(":"+str(":"+str(
print("Hour: "+str(
print("Minute: "+str(
print("Second: "+str(
print("MilliSecond: "+str(

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 and parses dateime from the webpage using the package dateparser.


from urllib.request import urlopen
import dateparser

time_url = urlopen(u'')
datetime ="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.


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

@Sai Kiran Sangam 2019-09-14 16:00:15

You can do so using ctime():

from time import time, ctime
t = time()


Sat Sep 14 21:27:08 2019

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

@champion-runner 2019-10-18 13:09:33

Current time of a timezone

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY =
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London =
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India =
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones

@ParaMeterz 2013-01-09 05:50:34

from datetime import datetime'%Y-%m-%d %H:%M:%S')

For this example, the output will be like this: '2013-09-18 11:16:32'

Here is the list of strftime directives.

@Ben 2018-08-13 20:08:17

This question doesn't need a new answer just for the sake of it ... a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.

For instance, the answer to the original question:

>>> import pendulum
>>> print(
>>> print('utc'))

There's a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There's a bit more than RFC and ISO formats there, though.

When we say local, though what do we mean? Well I mean:

>>> print(

Presumably most of the rest of you mean somewhere else.

And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It's worth consideration, particularly for both its ease of use and extensive documentation.

@Harley Holcombe 2009-01-06 04:57:05


>>> import datetime
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

>>> print(
2009-01-06 15:08:24.789150

And just the time:

datetime.time(15, 8, 24, 78915)

>>> print(

See the documentation for more information.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the leading datetime. from all of the above.

@Greg Lindahl 2018-10-01 21:41:45

It would be nice if this answer covered timezones (maybe UTC as an example) and perhaps begin with time.time().

@JiyuuSensei 2019-10-18 07:04:12

@Toskan the format was not part of the question, so it shouldn't be part of the answer. There's already a link provided to more documentation of the module which contains stuff like formatting.

@RTHarston 2019-10-29 15:04:26

Which version of Python was the original answer given in? Just typing in my Python 2.7 interactive console (IronPython hasn't updated yet) gives me the same behavior as the newer example using print() in the answer. I haven't successfully replicated what the original answer shows (datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)). (Not that I really want to, the print() behavior is preferred, but I am curious.)

@Harley Holcombe 2019-10-31 20:15:33

@BobVicktor: Python 2.7, 3.7 and 3.8 all give the same behaviour for me, not sure what you're seeing.

@RTHarston 2019-11-01 05:58:19

@HarleyHolcombe Hmm... maybe it is an IronPython thing? When I type on its own it prints it out the same was as your answer shows print(

@jobin 2019-10-12 18:09:19

import datetime

todays_date =
>>> 2019-10-12

# adding strftime will remove the seconds
current_time ='%H:%M')
>>> 23:38

@Sachin 2019-01-21 09:42:59

This is so simple. Try:

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

@Ethereal 2013-10-31 15:39:39

The previous answers are all good suggestions, but I find it easiest to use ctime():

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

This gives a nicely formatted string representation of the current local time.

@TheTechRobo36414519 2020-05-25 17:35:04

The OP asked how to get the time, not how to display it!

@nacholibre 2013-09-24 11:21:10

The quickest way is:

>>> import time
>>> time.strftime("%Y%m%d")

@user2030113 2014-05-20 07:13:36

>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time

@hlin117 2014-10-26 20:46:34

I think you mean to say ""

@user2030113 2014-11-04 10:02:25

yes it can be done as you said. ""%H:%M:%S:%MS")"

@ZF007 2019-06-13 20:23:03

%MS does not give you milliseconds!!

@Richie Bendall 2017-11-29 08:22:57

You can use this function to get the time (unfortunately it doesn't say AM or PM):

def gettime():
    from datetime import datetime
    return ((str(' ')[1]).split('.')[0]

To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:


def gethour():
    from datetime import datetime
    return (((str(' ')[1]).split('.')[0]).split(':')[0]


def getminute():
    from datetime import datetime
    return (((str(' ')[1]).split('.')[0]).split(':')[1]


def getsecond():
    from datetime import datetime
    return (((str(' ')[1]).split('.')[0]).split(':')[2]


def getmillisecond():
    from datetime import datetime
    return (str('.')[1]

@Anupam 2019-06-05 10:19:27

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 instead of The former is timezone 'aware' while the latter is not.

See this SO answer and the Django doc for details and rationale behind

from django.utils import timezone

now =

@durjoy 2017-11-07 06:17:52

if you are using numpy already then directly you can use numpy.datetime64() function.

import numpy as np

for only date:


or, if you are using pandas already then you can use pandas.to_datetime() function

import pandas as pd



@Ram Prajapati 2019-03-04 08:40:39

Get current date time attributes:

import datetime

currentDT =

print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" %
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)

import time;

ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks

@Bojan Petrovic 2018-01-16 14:45:15

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]
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.

@Toby Speight 2018-01-16 16:09:24

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.

@gerrit 2019-05-08 17:52:00

What is // doing here?

@Tom 2015-02-06 17:46:46

You can use the time module:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use the following code to give a more lengthy time:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

@prudhvi Indana 2017-09-22 12:45:57

Using pandas to get the current time, kind of overkilling the problem at hand:

import pandas as pd


2017-09-22 12:44:56.092642

@Vijay Dev 2009-01-06 05:02:43

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.

@Abhijeet Deshani 2016-07-14 05:50:20

import datetime
date_time = str(
date,time = date_time

date will print date and time will print time.

@motagirl2 2018-07-18 07:11:56

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the "timeit" module:

import timeit
start_time = timeit.default_timer()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

@kungphu 2018-07-06 08:24:22

Because no one has mentioned it yet, and this is something I ran into recently... a pytz timezone's fromutc() method combined with datetime's utcnow() is the best way I've found to get a useful current time (and date) in any timezone.

from datetime import datetime

import pytz

JST = pytz.timezone("Asia/Tokyo")

local_time = JST.fromutc(datetime.utcnow())

If all you want is the time, you can then get that with local_time.time().

@GraphicalDot 2018-08-30 17:27:15

Surprisingly, All the above answers didnt mention Time zones. you should also include strftime to get the format you wanted.

@kungphu 2018-08-31 21:59:08

I didn't include that since it's already been covered in other answers (and display formatting wasn't part of the question).

@Madhusudhan R 2018-03-01 11:34:55

By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file with the below content.

import datetime

currentDT =
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624

@theBuzzyCoder 2017-04-09 04:17:34

import datetime
date_time =

date =  # Gives the date
time = date_time.time()  # Gives the time

print date.year, date.month,
print time.hour, time.minute, time.second, time.microsecond

Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.

@theBuzzyCoder 2017-04-21 04:44:51

@snofty and @user1016274, if import datetime then it is\n if from datetime import datetime then it is

@y.selivonchyk 2016-07-18 09:45:50

I want to get the time with milliseconds. A simple way to get them:

import time, datetime

print(                         # 11:20:08.272239

# Or in a more complicated way
print(             # 11:20:08.272239
print('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

But I want only milliseconds, right? The shortest way to get them:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

@Greg Graham 2016-09-27 14:41:39

This works in Python 3: time.strftime("%H:%M:%S", time.localtime()) + '.{}'.format(int(time.time() % 1 * 1000))

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] What are metaclasses in Python?

33 Answered Questions

[SOLVED] What does if __name__ == "__main__": do?

44 Answered Questions

42 Answered Questions

[SOLVED] What does the "yield" keyword do?

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

40 Answered Questions

[SOLVED] How to get current time and date in Android

  • 2011-03-20 16:12:25
  • M7M
  • 1460703 View
  • 1133 Score
  • 40 Answer
  • Tags:   android date time

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

Sponsored Content