Short & Snazzy:
+ new Date()
A unary operator like plus
triggers the valueOf
method in the Date
object and it returns the timestamp (without any alteration).
Details:
On almost all current browsers you can use Date.now()
to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).
You can easily make a shim for this, though:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
To get the timestamp in seconds, you can use:
Math.floor(Date.now() / 1000)
Or alternatively you could use:
Date.now() / 1000 | 0
Which should be slightly faster, but also less readable.
(also see this answer or this with further explaination to bitwise operators).
I would recommend using Date.now()
(with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date
object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:
new Date().getTime()
Which you can then convert to seconds like this:
Math.round(new Date().getTime()/1000)
And you can also use the valueOf
method which we showed above:
new Date().valueOf()
Timestamp in Milliseconds
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();
console.log(timeStampInMs, Date.now());
Use:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150
And just the time:
>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)
>>> print(datetime.datetime.now().time())
15:08:24.789150
See the documentation for more information.
To save typing, you can import the datetime
object from the datetime
module:
>>> from datetime import datetime
Then remove the leading datetime.
from all of the above.
Best Answer
Local time or UTC? If it's UTC, the easiest way to do the conversion is to avoid the C time API entirely and use the formula in POSIX for seconds since the epoch:
Source: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15
If it's local time, the problem turns into hell due to the fact that
time_t
is not guaranteed to be represented as seconds since the epoch except on POSIX systems, and the fact that it's difficult to compute atime_t
value corresponding to the epoch (mktime
will not work because it uses local time). Once you compute thetime_t
for the epoch, though, it's just a matter of usingmktime
for the time value you parsed and then callingdifftime
.