[Datetime-SIG] local and utc time/date in python
alexander.belopolsky at gmail.com
Tue Aug 23 16:32:01 EDT 2016
On Tue, Aug 23, 2016 at 3:39 PM, Lenjoy <mars.lenjoy at gmail.com> wrote:
> summary for getting UTC time in sec:
> print time.time()
> print calendar.timegm(time.gmtime())
> print time.mktime(time.localtime())
> print calendar.timegm(datetime.datetime.utcnow().timetuple())
> print time.mktime(datetime.datetime.now().timetuple())
> Are all the functions above expected?
The time and calendar module precede the datetime module for about a
decade. If you use the datetime module, the "one obvious way" to get time
in "seconds since UNIX epoch" is to call the .timestamp() method of the
>>> datetime.now().timestamp() # Works in Python 3.6a
>>> datetime.now(timezone.utc).timestamp() # Faster and works since Python
Note that among the functions that you listed only the first will return
fractions of a second.
If you don't need the datetime module functionality and want to work with
floating point (or integer) timestamps - use time.time() method to get the
current time. The other functions of the time and calendar modules will
come handy when you need to convert between timestamps and human-readable
The datetime module was designed to operate on times directly in the
human-readable form and you are not expected to need to convert datetime
instances to timestamps except for interoperability with external libraries.
PS: From the use of the print statement in your summary, I conclude that
you still use Python 2.x. The datetime module has seen several
enhancements in the 3.x series and more features are still being added.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Datetime-SIG