What is the module/method used to get the current time?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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()
.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+):
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.
All good suggestions, but I find it easiest to use
ctime()
myself:This gives a nicely formatted string representation of current local time.
Quickest way is
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: