What is the module/method used to get the current time?
user46646user46646
How to get and format the current time in Python Time review. Time as we know is represented by several components. Get the current time in Python. There are two functions useful for retrieving current time on. Format the current time in Python. Once we have a time.structtime object.
33 Answers
12 next
Use:
And just the time:
See the documentation for more information.
To save typing, you can import the
datetime
object from the datetime
module:Then remove the leading
datetime.
from all of the above.Harley HolcombeHarley Holcombe
Sean JamesSean James
For this example, the output will be like this:
'2013-09-18 11:16:32'
Here is the list of
strftime
directives.ParaMeterzParaMeterz
Similar to Harley's answer, but use the
str()
function for a quick-n-dirty, slightly more human readable format:Community♦
Ray VegaRay Vega
The time
module
The
time
module provides functions that tells us the time in 'seconds since the epoch' as well as other utilities.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:
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:
You can hydrate timestamps into human readable form with
ctime
as well: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: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's utcnow
You can get a datetime object in UTC time, a global standard, by doing this:
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: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):And we see we can easily convert to timezones from the original utc object.
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: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. Aaron Hall♦Aaron Hall
Do
t
- float number, good for time interval measurement.
There is some difference for Unix and Windows platforms.
maxpmaxp
That outputs the current GMT in the specified format. There is also a
localtime()
method. This page has more details.
Vijay DevVijay Dev
All good suggestions, but I find it easiest to use
ctime()
myself:This gives a nicely formatted string representation of current local time.
EtherealEthereal
bluishbluish
nacholibrenacholibre
.isoformat()
is in the documentation, but not yet here(this is mighty similar to @Ray Vega's answer):emmagrasemmagras
Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?
If you live in the D.C. area (like me) the latency might not be too bad...
C8H10N4O2C8H10N4O2
Using pandas to get the current time, kind of overkilling the problem at hand:
Output:
prudhvi Indanaprudhvi Indana
This is what I ended up going with:
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).
Kristen G.Kristen G.
Do
dir(date)
or any variables including the package. You can get all the attributes and methods associated with the variable.theBuzzyCodertheBuzzyCoder
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:Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):
jfsjfs
Try the arrow module from http://crsmithdev.com/arrow/:
Or the UTC version:
To change its output, add .format():
For a specific timezone:
An hour ago:
Or if you want the gist.
Back2BasicsBack2Basics
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.The output looks like below:
Madhusudhan RMadhusudhan R
You can use the
time
module: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:
EpsilonXEpsilonX
if you are using numpy already then directly you can use numpy.datetime64() function.
for only date:
or, if you are using pandas already then you can use pandas.to_datetime() function
or,
durjoydurjoy
user2030113user2030113
I want to get the time with milliseconds. A simple way to get them:
But I want only milliseconds, right? The shortest way to get them:
Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:
y.selivonchyky.selivonchyk
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:
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:
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.
BenBen
If you just want the current timestamp in ms (for example, to measure execution time), you can also use the 'timeit' module:
motagirl2motagirl2
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:
It will print in HH:MM:SS format.
Amro elaswarAmro elaswar
You can use this function to get the time (unfortunately it doesn't say AM or PM):
To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:
Hour:
Minute:
Second:
Millisecond:
Richie BendallRichie Bendall
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.
If all you want is the time, you can then get that with
local_time.time()
.kungphukungphu
Abhijeet DeshaniAbhijeet Deshani
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.
Bojan PetrovicBojan Petrovic
Ram PrajapatiRam Prajapati
protected by casperOneApr 26 '12 at 12:03
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?