3537

How do I get the current time?

Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
user46646
  • 144,445
  • 43
  • 74
  • 84
  • 52
    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 – Sławomir Lenart Apr 29 '20 at 17:12
  • 5
    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](https://www.codingeek.com/tutorials/python/current-time/) – Hitesh Garg Aug 14 '21 at 14:26

51 Answers51

3623

Use datetime:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150

For just the clock time without the date:

>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150

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

>>> from datetime import datetime

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

Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Harley Holcombe
  • 166,540
  • 15
  • 68
  • 63
  • 47
    It would be nice if this answer covered timezones (maybe UTC as an example) and perhaps begin with time.time(). – Greg Lindahl Oct 01 '18 at 21:41
  • 10
    @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. – JiyuuSensei Oct 18 '19 at 07:04
  • Which version of Python was the original answer given in? Just typing `datetime.datetime.now()` 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.) – RTHarston Oct 29 '19 at 15:04
  • @BobVicktor: Python 2.7, 3.7 and 3.8 all give the same behaviour for me, not sure what you're seeing. – Harley Holcombe Oct 31 '19 at 20:15
  • @HarleyHolcombe Hmm... maybe it is an IronPython thing? When I type `datetime.now()` on its own it prints it out the same was as your answer shows `print(datetime.now())`... – RTHarston Nov 01 '19 at 05:58
  • Consider `import datetime as dt` if you want to use other datetime modules, such as `datetime.time`. – Chiel Mar 22 '21 at 15:10
  • @GregLindahl Timezone Aware: `datetime.datetime.now(tz=pytz.UTC).astimezone()` ... Or, something similar, like the actual timezone where the system is located. Alternately, `datetime.datetime.now(datetime.timezone.utc).astimezone()` or `datetime.datetime.utcnow().astimezone()` depending on the Python version and use case. – ingyhere Apr 09 '21 at 18:13
  • That is good to know about the time and date module but what is I want to use time and date from online time zone not from local system ? – UMANG BARAIYA Sep 09 '21 at 17:48
1119

Use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Sean James
  • 11,251
  • 1
  • 14
  • 8
  • 58
    Is this better/worse than @ParaMeterz's answer below? Why should we use the `time` module vs. the `datetime` module? – Nathan Apr 29 '18 at 16:17
  • 5
    It doesn't return current hour of my computer. – Saeed Oct 29 '18 at 11:51
  • 11
    This is UTC time, different from datetime module – Voyager Mar 12 '19 at 08:11
  • 32
    @Saeed: Use the function `localtime()` instead of the `gmtime()` to get your local time. – Jeyekomon Jul 03 '19 at 11:33
  • 4
    @frank See [related question](https://stackoverflow.com/q/7479777/9382524) on `datetime` vs. `time`. – Packard CPW Sep 30 '19 at 04:32
  • Note: `time.strftime("%Y-%m-%d %H:%M:%S")` defaults to use `time.localtime()`. Also, `time.gmtime()` sets DST(daylight saving time) flag to 0, whereas `time.localtime()` sets DST flag to 1 if DST applies to that time. – starriet Apr 30 '22 at 01:50
780
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

Example output: '2013-09-18 11:16:32'

See list of strftime directives.

Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
ParaMeterz
  • 8,837
  • 1
  • 18
  • 21
509

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(datetime.now())
'2011-05-03 17:45:35.177000'
Community
  • 1
  • 1
Ray
  • 179,335
  • 97
  • 219
  • 202
  • 1
    @ppperry, then just simply assign a variable to Ray's answer - like: _myTime = str(datetime.now())_. – Lukas Mar 27 '19 at 05:30
  • 4
    Not relevant; the "str" step is not within the scope of the question – pppery Apr 11 '19 at 21:06
  • 13
    @pppery Nor does the op say it isn't about getting a string of the time. The op doesn't say at all what they want to do with the time, so why is it a bad thing to show how to turn it in to a string? Most of the answers talk about getting a string from the time, so it appears to be a common use case, so why single out Ray's answer? What use is simply getting the time without knowing how to *do* anything with it? You can print it, or do math on it, and only a couple of the answers show how to do math on it, so I think printing/getting a string is a common use. ;-) (I know it is what I came for.) – RTHarston Oct 29 '19 at 15:21
  • 8
    The fact that this answer has more than 440 upvotes suggests that the minor addition of the string method _was_ useful to a lot of people. – John Jan 10 '20 at 20:09
  • 3
    The fact that 440 people were looking for content that is not an actual answer to the question does not make that content an answer to the question. – pppery Feb 21 '20 at 04:55
  • 3
    @pppery The fact that it is another way to answer the question which makes it RELEVANT to other people who has a similar question to this question. So there is nothing wrong with this :) – Ice Bear Dec 31 '20 at 15:20
483

How do I get the current time in Python?

The time module

The time module provides functions that tell 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()
1424233311.771502

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

time.ctime

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

datetime.datetime.now

The datetime.now 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.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
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 = datetime.datetime.now(pytz.utc)
>>> 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.now(datetime.timezone.utc)
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.

Russia Must Remove Putin
  • 337,988
  • 84
  • 391
  • 326
  • I think everyone can agree that `ctime` has got to be the weirdest way of formatting a datetime ever. Abbreviated day of the week and month, day of month, 24 hour h:m:s, and then a four digit year. Nerds that like to sort date strings, Americans, Europeans... everyone - yes, everyone - can find at least two things to be irritated about in that format. Although I'll use it because it's super easy. – ArtOfWarfare Sep 06 '20 at 03:32
  • As I say above regarding `ctime`: "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:" – Russia Must Remove Putin Sep 06 '20 at 05:16
149

Do

from time import time

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

There is some difference for Unix and Windows platforms.

Remi Guan
  • 20,142
  • 17
  • 60
  • 81
maxp
  • 5,214
  • 6
  • 27
  • 29
  • My result on Windows 10 home was 1576095264.2682993 - for Windows, this might just give the time in seconds. – hooman Dec 11 '19 at 20:16
116
>>> 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.

Georgy
  • 9,972
  • 7
  • 57
  • 66
Vijay Dev
  • 25,766
  • 20
  • 75
  • 96
83

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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ethereal
  • 2,404
  • 17
  • 20
78

The quickest way is:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
nacholibre
  • 3,523
  • 3
  • 29
  • 32
63

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
Rob I
  • 5,428
  • 2
  • 20
  • 28
bluish
  • 24,718
  • 26
  • 114
  • 174
50

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'
Tom
  • 874
  • 6
  • 19
47

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

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
emmagras
  • 1,276
  • 2
  • 17
  • 25
44

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('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

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

C8H10N4O2
  • 16,948
  • 6
  • 87
  • 123
  • 22
    @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 – sudobangbang Oct 28 '16 at 15:01
  • 1
    Excellent to have another source for time than the builtin clock! Even a good alternative to the more logical choice of NTP. – Roland Apr 27 '21 at 09:42
40

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

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

Output:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
Georgy
  • 9,972
  • 7
  • 57
  • 66
prudhvi Indana
  • 753
  • 7
  • 18
  • 1
    This method will be deprecated in future versions of pandas. Use the datetime module instead. – bfree67 Sep 29 '20 at 03:12
34

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

import numpy as np
str(np.datetime64('now'))

for only date:

str(np.datetime64('today'))

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

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))
durjoy
  • 1,609
  • 12
  • 24
33

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

Kristen G.
  • 683
  • 1
  • 7
  • 14
  • 2
    `strftime(time_format)` returns the current local time as a string that corresponds to the given `time_format`. Note: `time.strftime()` and `datetime.strftime()` support different directive sets e.g., [`%z` is not supported by `time.strftime()` on Python 2](https://docs.python.org/2/library/time.html#time.strftime). – jfs Jan 09 '15 at 23:36
  • 1
    Is it better practice to use datetime instead of time? – Kristen G. Jan 15 '15 at 20:09
  • 2
    Many `time` module functions are thin wrappers around corresponding C functions. `datetime` is a higher level and it is usually more portable. – jfs Jan 15 '15 at 20:19
31

datetime.now() 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 = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
jfs
  • 374,366
  • 172
  • 933
  • 1,594
  • FYI, it is not recommended to use `datetime.utcnow()` to represent the current time in UTC as that still returns a 'naive' datetime object -- instead, it is recommended to use `datetime.now(timezone.utc)` as that returns an 'aware' datetime object. See the Python docs for more details: https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow – Seth Jun 14 '21 at 18:35
  • @Seth notice that the Python 3.2+ solution uses `timezone.utc` already. Perhaps, now that Python 2.7 is EOLed the naive-datetime may be dropped – jfs Jun 15 '21 at 18:42
  • Ah, I didn't realize that was there purely for compatibility with Python 2.7 -- perhaps that should be clarified in the post? At least to me, it seemed like this post was implying that both the naive and aware methods were (still) equally acceptable ways to get the UTC time, which is why I pointed out that that's not what Python's (latest) documentation says. – Seth Jun 18 '21 at 17:45
25
import datetime
date_time = datetime.datetime.now()

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

print date.year, date.month, date.day
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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
theBuzzyCoder
  • 2,374
  • 2
  • 26
  • 26
  • @snofty and @user1016274, if `import datetime` then it is `datetime.datetime.now()`\n if `from datetime import datetime` then it is `datetime.now()` – theBuzzyCoder Apr 21 '17 at 04:44
25

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(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

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(pendulum.now().timezone_name)
Australia/Melbourne
>>>

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.

Ben
  • 3,697
  • 2
  • 23
  • 34
24
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
zwessels
  • 569
  • 1
  • 9
  • 24
user2030113
  • 455
  • 1
  • 5
  • 14
22

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 getDateTime1.py with the below content.

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Madhusudhan R
  • 301
  • 1
  • 4
  • 17
21

Try the arrow module from http://crsmithdev.com/arrow/:

import arrow
arrow.now()

Or the UTC version:

arrow.utcnow()

To change its output, add .format():

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

For a specific timezone:

arrow.now('US/Pacific')

An hour ago:

arrow.utcnow().replace(hours=-1)

Or if you want the gist.

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Back2Basics
  • 6,864
  • 1
  • 32
  • 42
  • 7
    beware that `arrow.now('Time/Zone')` may fail for some timezones (`arrow` uses [`dateutil` that has broken utc -> local conversions](https://github.com/dateutil/dateutil/issues/112) that are used inside `arrow.now()`. Note: [`pytz` has no such issue](http://stackoverflow.com/q/31886808/4279). Also, [there are other timezone-related issues](http://stackoverflow.com/questions/28087218/parse-date-and-time-from-string-with-time-zone-using-arrow/28095706#comment44593877_28095706) – jfs Nov 14 '15 at 09:00
19

To get exactly 3 decimal points for milliseconds 11:34:23.751 run this:

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

More context:

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

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%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)
y.selivonchyk
  • 7,824
  • 6
  • 47
  • 71
  • 1
    This works in Python 3: time.strftime("%H:%M:%S", time.localtime()) + '.{}'.format(int(time.time() % 1 * 1000)) – Greg Graham Sep 27 '16 at 14:41
19

Current time of a timezone

from datetime import datetime
import pytz

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

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

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

#list timezones
pytz.all_timezones
Jay Walker
  • 4,576
  • 5
  • 46
  • 51
champion-runner
  • 1,229
  • 1
  • 11
  • 25
18

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()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))
motagirl2
  • 571
  • 1
  • 10
  • 20
18

You can try the following

import datetime

now = datetime.datetime.now()
print(now)

or

import datetime

now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
Chathuranga Silva
  • 6,915
  • 2
  • 47
  • 54
Umutambyi Gad
  • 3,970
  • 3
  • 15
  • 34
17

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(datetime.now())).split(' ')[1]).split('.')[0]

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

Hour:

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

Minute:

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

Second:

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

Millisecond:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]
scrpy
  • 917
  • 6
  • 23
Richie Bendall
  • 5,657
  • 3
  • 32
  • 49
15

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

kungphu
  • 4,279
  • 3
  • 25
  • 36
  • Surprisingly, All the above answers didnt mention Time zones. you should also include strftime to get the format you wanted. – GraphicalDot Aug 30 '18 at 17:27
  • 1
    I didn't include that since it's already been covered in other answers (and display formatting wasn't part of the question). – kungphu Aug 31 '18 at 21:59
14
import datetime

todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12

# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38
Georgy
  • 9,972
  • 7
  • 57
  • 66
Jobin James
  • 766
  • 7
  • 12
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
Littin Rajan
  • 772
  • 1
  • 8
  • 20
11

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.

Noah Broyles
  • 864
  • 1
  • 9
  • 24
10

try this one:-

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
RITIK KUMAR
  • 127
  • 1
  • 6
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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Amro elaswar
  • 3,305
  • 2
  • 21
  • 36
9
import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date will print date and time will print time.

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()
Georgy
  • 9,972
  • 7
  • 57
  • 66
Anupam
  • 13,804
  • 17
  • 61
  • 90
8

This is so simple. Try:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]
Georgy
  • 9,972
  • 7
  • 57
  • 66
Sachin
  • 800
  • 8
  • 20
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.

Georgy
  • 9,972
  • 7
  • 57
  • 66
Bojan Petrovic
  • 199
  • 2
  • 4
  • 1
    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. – Toby Speight Jan 16 '18 at 16:09
  • 1
    What is `//` doing here? – gerrit May 08 '19 at 17:52
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
Georgy
  • 9,972
  • 7
  • 57
  • 66
Ram Prajapati
  • 1,463
  • 8
  • 8
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.

Samuel Nde
  • 2,242
  • 2
  • 21
  • 23
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
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
Lucas Urban
  • 463
  • 3
  • 12
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
Ransaka Ravihara
  • 1,471
  • 1
  • 10
  • 26
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(')'))
Harsh
  • 121
  • 1
  • 1
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.

James McGuigan
  • 6,794
  • 4
  • 23
  • 25
2

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"))
Tom Carrick
  • 5,900
  • 13
  • 52
  • 76
  • The latest version of Python available for download is 3.8.5! https://www.python.org/downloads/ – Sandun Aug 22 '20 at 13:49
  • 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: https://docs.python.org/3.9/whatsnew/3.9.html – Tom Carrick Aug 23 '20 at 18:03
2

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)
Kofi
  • 882
  • 1
  • 7
  • 18
1

Gets the current time and converts it to string:

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Matei Piele
  • 321
  • 1
  • 11
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.

Faraaz Kurawle
  • 923
  • 3
  • 22
0

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)
Sankar guru
  • 842
  • 1
  • 7
  • 14
0

This should work

import time

now = datetime.now()

current_time = now.strftime("%H:%M:%S")

print("The current time is", current_time)

Mr. Day
  • 51
  • 1
  • 7
0

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

import pandas as pd
pd.Timestamp.now()

And just the time:

pd.Timestamp.now().strftime('%H:%M:%S')
rachwa
  • 354
  • 1
  • 11