By user46646

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

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


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

@BobVicktor 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.

@BobVicktor 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(

@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"))

@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 Verma 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.

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

The quickest way is:

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

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

@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?

@EpsilonX 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.

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

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

@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(pendulum.utcnow())

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.

@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))

@Back2Basics 2015-11-14 02:02:45

Try the arrow module from

import arrow

Or the UTC version:


To change its output, add .format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

For a specific timezone:'US/Pacific')

An hour ago:


Or if you want the gist.

>>> '2 years ago'

@jfs 2015-11-14 09:00:04

beware that'Time/Zone') may fail for some timezones (arrow uses dateutil that has broken utc -> local conversions that are used inside Note: pytz has no such issue. Also, there are other timezone-related issues

@Amro elaswar 2015-05-01 01:39:08

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.

@emmagras 2013-06-25 00:38:25

.isoformat() is in the documentation, but not yet here (this is mighty similar to @Ray Vega's answer):

>>> import datetime

@Samuel Nde 2018-05-24 20:27:29

First import the datetime module from datetime

from datetime import datetime

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


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;


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

@C8H10N4O2 2016-08-19 19:45:08

Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?

import requests
from lxml import html

page = requests.get('')
tree = html.fromstring(page.content)

If you live in the D.C. area (like me) the latency might not be too bad...

@sudobangbang 2016-10-28 15:01:21

@C8H10N4O2 While you are correct that the other answers assume that your computer already knows the correct time, this answer assumes that the computer has a connection to the internet, that you are in the U.S., and that they will never take down that file/alter the link. Far more assumptions in this answer than accepted. Still clever none the less

@Aaron Hall 2015-02-18 05:08:34

How do I get the current time in Python?

The time module

The time module provides functions that tells us the time in "seconds since the epoch" as well as other utilities.

import time

Unix Epoch Time

This is the format you should get timestamps in for saving in databases. It is a simple floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we'll be looking at next:

>>> time.time()

This timestamp does not account for leap-seconds, so it's not linear - leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.

This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you'll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).


You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don't rely on this to be standard across all systems, as I've seen others expect). This is typically user friendly, but doesn't typically result in strings one can sort chronologically:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

You can hydrate timestamps into human readable form with ctime as well:

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

This conversion is also not good for record-keeping (except in text that will only be parsed by humans - and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).

datetime module

The datetime module is also quite useful here:

>>> import datetime

The is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:

datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(
2015-02-17 23:43:51.782461

datetime's utcnow

You can get a datetime object in UTC time, a global standard, by doing this:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)

datetime timezone aware

However, none of the datetime objects we've created so far can be easily converted to various timezones. We can solve that problem with the pytz module:

>>> import pytz
>>> then =
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):

datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

And we see we can easily convert to timezones from the original utc object.

>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00

You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace, this is done blindly), but these are more last resorts than best practices:

>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.

One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.

The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.

If you're displaying the time with Python for the user, ctime works nicely, not in a table (it doesn't typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.

Related Questions

Sponsored Content

30 Answered Questions

[SOLVED] Daylight saving time and time zone best practices

41 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

38 Answered Questions

[SOLVED] Get current time and date on Android

  • 2011-03-20 16:12:25
  • M7M
  • 1321627 View
  • 1049 Score
  • 38 Answer
  • Tags:   android date time

38 Answered Questions

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

27 Answered Questions

[SOLVED] How do I get time of a Python program's execution?

  • 2009-10-12 23:56:47
  • john2x
  • 928046 View
  • 822 Score
  • 27 Answer
  • Tags:   python time

26 Answered Questions

[SOLVED] Measure time elapsed in Python

38 Answered Questions

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

12 Answered Questions

[SOLVED] How can I make a time delay in Python?

5 Answered Questions

[SOLVED] What do 'real', 'user' and 'sys' mean in the output of time(1)?

13 Answered Questions

[SOLVED] Find current directory and file's directory

  • 2011-02-28 01:51:21
  • John Howard
  • 2697845 View
  • 1987 Score
  • 13 Answer
  • Tags:   python directory

Sponsored Content