How to get UTC time in Python?
Question: I've search a bunch on StackExchange for a solution but nothing does quite
what I need. In JavaScript, I'm using the following to calculate UTC time
since Jan 1st 1970:

    
    
    function UtcNow() {
        var now = new Date();
        var utc = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
        return utc;
    }
    

What would be the equivalent Python code?


Answer: Try this code that uses
[datetime.utcnow()](http://docs.python.org/2/library/datetime.html#datetime.datetime.utcnow):

    
    
    from datetime import datetime
    datetime.utcnow()
    

For your purposes when you need to calculate an amount of time spent between
two dates all that you need is to substract end and start dates. The results
of such substraction is a [timedelta
object.](http://docs.python.org/2/library/datetime.html#timedelta-objects)

From the python docs:

    
    
    class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    

And this means that by default you can get any of the fields mentioned in it's
definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks.
Also timedelta instance has total_seconds() method that:

> Return the total number of seconds contained in the duration. Equivalent to
> (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*_6) / 10_ *6
> computed with true division enabled.

