[Datetime-SIG] local and utc time/date in python

Alexander Belopolsky 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?
>

Yes.

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 object:

>>> datetime.now().timestamp()   # Works in Python 3.6a
1471983108.547574
>>> datetime.now(timezone.utc).timestamp()  # Faster and works since Python
3.5
1471983125.307036

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

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...
URL: <http://mail.python.org/pipermail/datetime-sig/attachments/20160823/34e763e8/attachment.html>


More information about the Datetime-SIG mailing list