How to get UTC time in Python?

PythonDatetime

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Try this code that uses 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.

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) * > 106) / 106 computed with true division enabled.

Solution 2 - Python

Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow().

from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)

Solution 3 - Python

In the form closest to your original:

import datetime

def UtcNow():
    now = datetime.datetime.utcnow()
    return now

If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:

return (now - datetime.datetime(1970, 1, 1)).total_seconds()

Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:

utc_now = datetime.datetime.utcnow

Solution 4 - Python

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

Solution 5 - Python

Timezone aware with zero external dependencies:

from datetime import datetime, timezone

def utc_now():
    return datetime.utcnow().replace(tzinfo=timezone.utc)

Solution 6 - Python

From datetime.datetime you already can export to timestamps with method strftime. Following your function example:

import datetime
def UtcNow():
    now = datetime.datetime.utcnow()
    return int(now.strftime("%s"))

If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))

Solution 7 - Python

you could use datetime library to get UTC time even local time.

import datetime

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

Solution 8 - Python

why all reply based on datetime and not time? i think is the easy way !

import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames ClarkeView Question on Stackoverflow
Solution 1 - PythonArtsiom RudzenkaView Answer on Stackoverflow
Solution 2 - PythonTim RichardsonView Answer on Stackoverflow
Solution 3 - PythonMark RansomView Answer on Stackoverflow
Solution 4 - PythonMikeLView Answer on Stackoverflow
Solution 5 - PythonCesar CanassaView Answer on Stackoverflow
Solution 6 - PythonhectorcantoView Answer on Stackoverflow
Solution 7 - PythonHCHOView Answer on Stackoverflow
Solution 8 - PythonAmine RizkView Answer on Stackoverflow