How to get current time in Python?

user46646 Source

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



answered 9 years ago Harley Holcombe #1

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

And just the time:

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

The same but slightly more compact:


See the documentation for more info.

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

>>> from datetime import datetime

Then remove the leading datetime. from all the above.

answered 9 years ago Sean James #2

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

answered 9 years ago Vijay Dev #3

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

answered 9 years ago maxp #4


from time import time

t = time()
  • t - float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.

answered 7 years ago bluish #5

If you need current time as a time object:

>>> import datetime
>>> now =
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

answered 7 years ago Ray Vega #6

Similar to Harley's answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

>>> from datetime import datetime
>>> str(
'2011-05-03 17:45:35.177000'

answered 5 years ago ParaMeterz #7

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

answered 5 years ago emmagras #8

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

>>>import datetime

answered 4 years ago nacholibre #9

Quickest way is

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

answered 4 years ago Ethereal #10

All good suggestions, but I find it easiest to use ctime() myself:

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 current local time.

answered 4 years ago user2030113 #11

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

answered 3 years ago jfs #12 returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):

from datetime import datetime, timezone

now =
print(now) # -> 2014-12-23 01:49:25.837541+03:00

answered 3 years ago Kristen G. #13

This is what I ended up going with:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).

strftime format code table

answered 3 years ago EpsilonX #14

You can use the time module.

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

>>> 06/02/2015

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

You could also use to give a more lengthy time.

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

answered 3 years ago Aaron Hall #15

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.

answered 3 years ago Amro elaswar #16

This is what i use to get the time without having to format , some people dont like the split method but it is useful here :

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

Will print in HH:MM:SS format

answered 2 years ago Back2Basics #17

Try the arrow module from

import arrow

or the utc version


to change it's 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'

answered 2 years ago Abhijeet Deshani #18

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

date will print date and time will print time.

answered 2 years ago yauheni_selivonchyk #19

I am a simple man and I want to get time with milliseconds. 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? 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)

answered 2 years ago C8H10N4O2 #20

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

answered 11 months ago theBuzzyCoder #21

import datetime
date_time =

date =  # gives date
time = date_time.time()  # gives 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 to the variable.

answered 6 months ago prudhvi Indana #22

using pandas to get current time, kind of over killing the problem at hand.

import pandas as pd
print (
print (
print (
print (
print (
print (
print (
print (
print (


2017-09-22 12:44:56.092642

answered 5 months ago Ani Menon #23

Simple and easy:

Using datetime module,

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


2017-10-17 23:48:55


Using time,

import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))


2017-10-17 18:22:26

answered 4 months ago durjoy #24

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



answered 4 months ago Richie Bendall #25

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]

Also To Get The Hours, Minutes, Seconds And Milliseconds To Merge Later, You Can Use These Functions:


def gethour():
        from datetime import datetime
        return 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 return (str('.')[1]

answered 2 months ago Bojan Petrovic #26

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.

answered 3 weeks ago Madhusudhan R #27

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

import datetime

currentDT =
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624

comments powered by Disqus