Python提供了不同的包(datetime, time, calendar)来处理时间。我犯了一个大错误,使用以下命令获取当前的GMT时间time.mktime(datetime.datetime.utcnow().timetuple()))

用Unix时间戳获取当前格林尼治时间的简单方法是什么?


当前回答

Python2和python3

使用时间模块是很好的

import time
int(time.time())

1573708436

你也可以使用datetime模块,但是当你使用strftime('%s')时,strftime会将时间转换为你的本地时间!

python2

from datetime import datetime
datetime.utcnow().strftime('%s')

python3

from datetime import datetime
datetime.utcnow().timestamp()

其他回答

#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

输出:1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

输出:1572878043

在这里,我们可以看到第一个例子给出的时间比第二个更准确。 这里我用的是第一个。

import time

int(time.time()) 

输出:

1521462189
from datetime import datetime as dt
dt.utcnow().strftime("%s")

输出:

1544524990

Python 3秒微秒十进制分辨率:

from datetime import datetime
print(datetime.now().timestamp())

Python 3整数秒:

print(int(datetime.now().timestamp()))

datetime.utcnow().timestamp()警告!

Datetime.utcnow()是非时区感知对象。参考资料:https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

例如UTC凌晨1点:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!

我喜欢这个方法:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

这里发布的其他方法要么不保证在所有平台上为您提供UTC,要么只报告整个秒数。如果你想要完整的分辨率,这个可以做到微秒级。